Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

12.2 KB
Raw Blame
import { inspectProject, resolveProjectHint } from "@/lib/host/projects-api";
import { discardWorkflowWorktreeIfUnchanged } from "@/lib/host/project-worktree";
import { activeWorkflowForActor, cancelWorkflow, finishWorkflow, workflowStepProvenance } from "@/lib/workflow";
import { getAgentSession } from "@/lib/agent/session-store";
import { agentSessionLabel } from "@/lib/agent/session-name";
import { disarmLocalAgentStandbyWorkflow } from "@/lib/agent/local-agent-standby";
import { assessAutomationPromotion, buildAutomationScriptManifest, workflowCleanupGuidance } from "@/lib/orchestration/automation";
import { classifyTask } from "@/lib/orchestration/classifier";
import { buildEvidenceReceipt, validateEvidenceReceipt } from "@/lib/orchestration/evidence";
import { upsertRepoMemory } from "@/lib/orchestration/repo-memory";
import { writeAutomationScript, writeEvidenceReceipt, writePortableRecipe } from "@/lib/orchestration/repo-memory-artifacts";
import type { McpTool } from "./tool-kit";
import { opt, S, str } from "./tool-kit";
import { evidenceInput, evidenceSchema, WORKFLOW_PROGRESS_OUTPUT, workflowProgress } from "./tools-learning-shared";

async function workflowCleanupResult(workflow: { project?: string; orchestration?: { isolation?: "direct" | "optional-worktree" | "isolated-worktree"; workspacePath?: string; baseCommit?: string; affectedPaths?: string[]; reservedResources?: string[] } }) {
  const guidance = workflowCleanupGuidance(workflow.orchestration);
  if (!workflow.project || !workflow.orchestration?.workspacePath || workflow.orchestration.isolation !== "isolated-worktree") return guidance;
  try {
    const autoRemoved = await discardWorkflowWorktreeIfUnchanged({
      canonicalPath: workflow.project, workspacePath: workflow.orchestration.workspacePath, baseCommit: workflow.orchestration.baseCommit,
    });
    return autoRemoved ? {
      ...guidance, autoRemoved: true, worktreeCleanupRequired: false,
      instruction: "Unused clean task worktree was removed automatically after workflow close.",
    } : { ...guidance, autoRemoved: false };
  } catch (error) {
    return { ...guidance, autoRemoved: false, warning: error instanceof Error ? error.message : String(error) };
  }
}

export const WORKFLOW_LIFECYCLE_TOOLS: McpTool[] = [
  {
    name: "workflow_status",
    description: "Return a redacted live status snapshot for one workflow; arguments, file contents and credentials stay hidden.",
    scope: "read",
    annotations: { readOnlyHint: true, idempotentHint: true },
    outputSchema: WORKFLOW_PROGRESS_OUTPUT,
    meta: {
      ui: { visibility: ["app"] },
      "openai/widgetAccessible": true,
    },
    limit: { key: "workflow.status", max: 30, windowMs: 60_000 },
    inputSchema: S({
      workflow_id: { type: "string", description: "workflow_start id." },
    }),
    run: async (a, context) => {
      const workflowId = str(a, "workflow_id");
      const workflow = await activeWorkflowForActor(context.workflowActor ?? context.actor, workflowId);
      if (!workflow) {
        return { active: false, workflowId, stepCount: 0, steps: [] };
      }
      return workflowProgress(workflow, true)!;
    },
  },
  {
    name: "workflow_cancel",
    description: "Cancel one exact active workflow without saving a learned recipe.",
    scope: "write",
    annotations: { idempotentHint: false },
    actionContract: { phase: "mutate", target: "workflow", sourceOfTruth: "live", validators: ["workflow-ownership"], confirmation: "contextual", concurrency: "contextual", presentation: "structured" },
    limit: { key: "workflow.memory", max: 30, windowMs: 60_000 },
    audit: { action: "workflow.cancel" as const, targetArg: "workflow_id" },
    inputSchema: S({
      workflow_id: { type: "string", description: "workflow_start id." },
      reason: { type: "string", description: "Optional reason; no secrets." },
    }, ["workflow_id"]),
    run: async (a, context) => {
      const workflowActor = context.workflowActor ?? context.actor;
      const cancelled = await cancelWorkflow({
        actor: workflowActor,
        workflowId: str(a, "workflow_id"),
        reason: opt(a, "reason"),
      });
      if (workflowActor)
        await disarmLocalAgentStandbyWorkflow(workflowActor, cancelled.workflow.id, "workflow cancelled");
      return { ...cancelled, cleanup: await workflowCleanupResult(cancelled.workflow) };
    },
  },
  {
    name: "workflow_finish",
    description: "Finish one verified workflow. MSO saves redacted evidence, memory, recipe quality and safe automation-learning metadata.",
    scope: "write",
    annotations: { idempotentHint: false },
    actionContract: { phase: "verify", target: "workflow", sourceOfTruth: "live", validators: ["evidence-receipt", "risk-policy"], confirmation: "none", concurrency: "contextual", presentation: "structured" },
    limit: { key: "workflow.memory", max: 30, windowMs: 60_000 },
    audit: { action: "workflow.finish" as const, targetArg: "workflow_id" },
    inputSchema: S({
      workflow_id: { type: "string", description: "workflow_start id." },
      summary: { type: "string", description: "Outcome and verification; no secrets." },
      success: { type: "boolean", description: "True only after verification." },
      evidence: evidenceSchema(),
    }, ["workflow_id", "summary", "success"]),
    run: async (a, context) => {
      const actor = context.workflowActor ?? context.actor;
      const workflowId = str(a, "workflow_id");
      const summary = str(a, "summary");
      const success = a.success === true;
      const workflow = await activeWorkflowForActor(actor, workflowId);
      if (!workflow) throw new Error("workflow_id was not found for this MSO session");
      const project = workflow.project ? await resolveProjectHint(workflow.project).catch(() => null) : null;
      const finalRepository = project
        ? await inspectProject(project, { includeGitStatus: context.scope === "exec" }).catch(() => undefined)
        : undefined;
      const risk = workflow.orchestration?.risk ?? classifyTask({
        intent: workflow.intent, constraints: workflow.constraints, scope: context.scope,
      }).risk;
      const suppliedEvidence = evidenceInput(a.evidence);
      const receipt = buildEvidenceReceipt({
        workflow, summary, success, evidence: suppliedEvidence,
        finalCommit: finalRepository?.git.head?.sha,
      });
      const validation = validateEvidenceReceipt(receipt, { success, risk });
      // Backward compatibility: only workflows created with RASMIC metadata get the new
      // hard gate. Legacy in-flight workflows can still close under their old contract.
      if (workflow.orchestration && !validation.valid) throw new Error(validation.errors.join("; "));

      let stepProvenance: ReturnType<typeof workflowStepProvenance> | undefined;
      if (context.principal && context.sessionId) {
        const sourceSession = await getAgentSession(context.principal, context.sessionId).catch(() => null);
        if (sourceSession) {
          stepProvenance = workflowStepProvenance(
            sourceSession, workflowId, agentSessionLabel(sourceSession.name, sourceSession.title, sourceSession.cwd), workflow.steps, receipt.ref,
          );
        }
      }
      const finished = await finishWorkflow({
        actor, recipeActor: context.recipeActor ?? context.actor, workflowId, summary, success, stepProvenance,
      });
      if (actor) await disarmLocalAgentStandbyWorkflow(actor, workflowId, "workflow finished");
      const automation = assessAutomationPromotion(finished.recipe);
      const persistenceWarnings: string[] = [];
      let evidencePath: string | undefined;
      let taskMemoryId: string | undefined;
      let scriptPath: string | undefined;
      const explicitEvidence = Boolean(suppliedEvidence && [
        suppliedEvidence.tests, suppliedEvidence.build, suppliedEvidence.deployment,
        suppliedEvidence.health, suppliedEvidence.artifacts, suppliedEvidence.manualVerification,
        suppliedEvidence.knownRisks,
      ].some((items) => Array.isArray(items) && items.length > 0));
      const shouldPersistEvidence = risk !== "low" || !success || explicitEvidence;
      const shouldPersistTaskMemory = shouldPersistEvidence || workflow.orchestration?.memoryRelevance !== "low";
      const memoryScope = [...new Set([
        ...(workflow.orchestration?.affectedPaths ?? []),
        ...(workflow.orchestration?.changedPaths ?? []),
      ])];

      if (project) {
        try {
          if (shouldPersistEvidence) evidencePath = await writeEvidenceReceipt(project.path, receipt);
          if (shouldPersistTaskMemory) {
            const taskMemory = await upsertRepoMemory(project.path, {
            kind: "task",
            title: `${success ? "Completed" : "Failed"}: ${workflow.intent.slice(0, 120)}`,
            summary,
            source: "system",
            result: success ? "pass" : "fail",
            status: success ? "confirmed" : "active",
            confidence: success ? 0.9 : 1,
            importance: risk === "high" ? 0.9 : risk === "medium" ? 0.7 : 0.5,
            lastVerified: success ? receipt.createdAt : undefined,
            scope: memoryScope,
            tags: ["workflow", risk, workflow.orchestration?.complexity ?? "unknown"],
            commit: receipt.finalCommit,
            environment: receipt.environment,
            happened: summary,
            ...(success ? { worked: summary } : { failed: summary }),
            learned: success ? "Result is backed by the attached Evidence Receipt." : "Do not treat this workflow as healthy until the failure is resolved and re-verified.",
            reuse: automation.stage === "verified" ? "A verified reusable recipe exists for similar work; prefer it before replanning from scratch." : "Retrieve this task memory when similar scope is attempted again.",
            });
            taskMemoryId = taskMemory.id;
          }
          if (!success) {
            await upsertRepoMemory(project.path, {
              kind: "failure", title: `Workflow failure: ${workflow.intent.slice(0, 120)}`, summary, source: "system",
              result: "fail", status: "active", confidence: 1, importance: 0.9,
              scope: memoryScope, tags: ["workflow-failure", risk], commit: receipt.finalCommit,
              failed: summary, reuse: "Check this failure before repeating the same approach.",
            });
          }
          if (automation.stage !== "observed") {
            await writePortableRecipe(project.path, {
              schemaVersion: 1, id: finished.recipe.id, intent: finished.recipe.intent, summary: finished.recipe.summary,
              stage: automation.stage, attempts: finished.recipe.attempts, successes: finished.recipe.successes, failures: finished.recipe.failures,
              successRate: automation.successRate, bestSteps: finished.recipe.bestSteps, candidatePool: finished.recipe.candidatePool, quality: finished.recipe.quality, updatedAt: finished.recipe.updatedAt,
            }, finished.recipe.id);
          }
          if (automation.scriptCandidate) {
            const script = buildAutomationScriptManifest(finished.recipe, { tested: false });
            scriptPath = await writeAutomationScript(project.path, script, script.id, true);
          }
        } catch (error) {
          persistenceWarnings.push(error instanceof Error ? error.message : String(error));
        }
      }

      return {
        ...finished,
        evidence: { receipt, valid: validation.valid, errors: validation.errors, path: evidencePath },
        automation,
        metrics: {
          toolCalls: workflow.steps.length,
          executionDurationMs: finished.currentDurationMs,
          retries: finished.recipe.lastQuality?.retries ?? 0,
          memoryHits: workflow.orchestration?.memoryHits ?? 0,
          contextEstimateTokens: workflow.orchestration?.contextEstimateTokens ?? 0,
          recipeRecommended: Boolean(workflow.orchestration?.recipeUsed),
          recipeRouteMatched: finished.reuse?.routeMatched ?? false,
          recipeReuseScore: finished.reuse?.score ?? 0,
          recipeStage: automation.stage,
          scriptCandidateCreated: Boolean(scriptPath),
        },
        repoMemory: { taskMemoryId, scriptPath, warnings: persistenceWarnings },
        cleanup: await workflowCleanupResult(workflow),
      };
    },
  },
];