eust-w 4cffd71be8 ✨ Learn project skills from runs, and export a wish's report
- Skills: per-project know-how the platform proposes from each succeeded
  run (in the background, or on request from a run), people confirm,
  edit, disable, delete or write; active ones enter later prompts
- Export one skill as SKILL.md, or all as a zip with a directory per
  skill, as .claude/skills/ expects
- A wish's report: every run, its stage timeline, the agent's plan,
  replies, commands, changed files and model usage, the change, the
  checks, failures, reviews and releases, and the full event log, as
  Markdown, or laid out for printing to PDF

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 03:57:24 +08:00

238 lines
8.9 KiB
TypeScript

import path from 'node:path';
import type { Project, ProviderId, Run, VerificationProfile, WaitingReason } from '@wishforge/contracts';
import type { AgentBundleConfig, PromptSkill } from '@wishforge/agent';
import {
GitWorkspace,
readLocalPocBindings,
localPocForProject,
RuntimeError,
safeIdentifier,
type CheckPodConfig,
type CommandExecutor,
type HostCheckSandbox,
type PortableCheckpoint,
type ProviderAdapter,
} from '@wishforge/runtime';
import { ControlPlaneClient, ControlPlaneError } from './client.js';
import { RunStopped } from './lease.js';
export interface RunInput {
tenantId: string;
runId: string;
generation: string;
}
export interface DeliveryConfig {
imageRepository: string;
architecture: 'linux/amd64' | 'linux/arm64';
environmentId: string;
dockerfile?: string;
sourceContext?: string;
containerPort?: number;
healthPath?: string;
}
export interface RunContext {
run: Run;
project: Project & { deliveryConfig?: DeliveryConfig };
workspace?: string;
checkpoint?: PortableCheckpoint | null;
providerCredential?: {
apiKey?: string;
baseUrl?: string;
model?: string;
metering?: 'proxy';
env?: Record<string, string>;
};
gitCredential?: { token: string; username?: 'x-access-token' };
verificationCommands?: string[][];
installCommands?: string[][];
verificationProfile?: VerificationProfile;
verificationProfileDigest?: string;
verificationProfileRequired?: boolean;
bundleConfig?: AgentBundleConfig;
lessons?: string[];
/** The project's active skills, most recently changed first. */
skills?: PromptSkill[];
delivery?: {
release?: { id: string; status: string };
verificationEvidenceId?: string;
buildEvidenceId?: string;
environmentId?: string;
/** The target branch commit the run integrated onto. */
integrationBaseCommit?: string;
/** The commit of the release the environment runs now, if any. */
deployedCommit?: string;
};
}
export interface ActivityOutcome {
status: 'waiting' | 'failed' | 'canceled' | 'paused' | 'verify' | 'release' | 'repair' | 'complete';
/** Set when the activity found why the run must wait; absent when the control plane already recorded it. */
reason?: WaitingReason;
detail?: string;
verificationEvidenceId?: string;
buildEvidenceId?: string;
environmentId?: string;
}
/** `host` runs commands as the current user (development only); `kata` is the per-run production sandbox. */
export type SandboxMode = 'host' | 'kata';
export interface WorkerConfig {
localPocBindingFile?: string;
controlPlaneUrl: string;
workerToken?: string;
verifierToken?: string;
deployerToken?: string;
workerId: string;
workspaceRoot: string;
isolatedProviderHomeRoot: string;
/** Unset for shared workers (coordinator, deployer), which never execute project code. */
sandboxMode?: SandboxMode;
sandboxRunId?: string;
sandboxTenantId?: string;
sandboxGeneration?: string;
verifierBinary?: string;
/** Executables of the CLI executors (see providers.ts). */
providerBinaries?: Partial<Record<ProviderId, string>>;
/** Trusted local operator's Claude login; only supplied to development host executors. */
claudeAuthHome?: string;
/** Operator opt-in to Bash in Claude Code's own sandbox (see claudeCommandSandbox in providers.ts). */
claudeCommandSandbox?: { readable: string[]; env: Record<string, string> };
/** Operator opt-in to a macOS sandbox for host checks and installations (see host-checks.ts). */
hostCheckSandbox?: HostCheckSandbox;
/** Operator opt-in, on a host that is itself a Pod, to a check Pod per workspace (see host-checks.ts). */
hostCheckPods?: CheckPodConfig;
dockerConfig?: string;
/** Docker CLI context of the image builder; operator configuration, never project settings. */
dockerContext?: string;
/** A remote builder daemon (tcp://host:port) and its TLS files, for sandboxes without a local Docker. */
dockerHost?: string;
dockerTlsDirectory?: string;
/** The operator's egress proxy that dependency installations go through. */
installProxy?: string;
allowLocalGitHttp?: boolean;
resourceLimits?: { cpuMilli: number; memoryMiB: number; storageMiB?: number };
fetcher?: typeof fetch;
/** How often an execution lease is renewed; tests shorten it. */
heartbeatMs?: number;
/** Process execution, replaceable like `fetcher` and `providerFactory` for tests. */
execute?: CommandExecutor;
providerFactory?: (context: RunContext, isolatedHome: string) => ProviderAdapter;
}
export function client(config: WorkerConfig, input: RunInput, token = config.workerToken) {
safeIdentifier(input.tenantId);
safeIdentifier(input.runId);
safeIdentifier(input.generation);
return new ControlPlaneClient(config.controlPlaneUrl, input.tenantId, token ?? '', config.fetcher);
}
export const waiting = (reason: WaitingReason, detail: string): ActivityOutcome => ({
status: 'waiting',
reason,
detail,
});
/** Project code only runs in a sandbox provisioned for exactly this tenant, run and generation. */
export function sandboxMismatch(config: WorkerConfig, input: RunInput): string | undefined {
if (!config.sandboxMode) return 'This worker is not a per-run sandbox; WF_SANDBOX_MODE must be host or kata.';
if (
config.sandboxRunId !== input.runId ||
config.sandboxTenantId !== input.tenantId ||
config.sandboxGeneration !== input.generation
)
return 'This sandbox was provisioned for a different run or generation.';
}
export function stoppedOutcome(run: Pick<Run, 'status'>): ActivityOutcome | undefined {
if (run.status === 'succeeded') return { status: 'complete' };
if (run.status === 'failed' || run.status === 'canceled' || run.status === 'paused') return { status: run.status };
}
export function tenantRoot(config: WorkerConfig, input: RunInput) {
return path.join(config.workspaceRoot, safeIdentifier(input.tenantId));
}
export function gitFor(config: WorkerConfig, context: RunContext, execute: CommandExecutor) {
const poc = localPocForProject(readLocalPocBindings(config.localPocBindingFile), context.project);
return new GitWorkspace(execute, {
localSshTransport: poc
? {
repositoryUrl: poc.repositoryUrl,
sshUrl: 'ssh://git@gitea.d-robotics.cc/longtao.wu/droboticflow.git',
home: poc.gitHome,
}
: undefined,
allowLocalHttp: config.allowLocalGitHttp,
credential:
context.gitCredential && context.project.repositoryUrl
? { ...context.gitCredential, repositoryUrl: context.project.repositoryUrl }
: undefined,
});
}
const GIT_STORAGE = new Set([
'INVALID_REPOSITORY',
'REPOSITORY_TRANSPORT_UNSUPPORTED',
'REPOSITORY_POLICY',
'TARGET_BRANCH_UNAVAILABLE',
'SOURCE_BRANCH_UNAVAILABLE',
'INVALID_REF',
'CHECKPOINT_BASE_UNAVAILABLE',
'POC_SOURCE_REWRITTEN',
]);
const VERIFICATION = new Set([
'VERIFICATION_UNCONFIGURED',
'VERIFICATION_PROFILE_INVALID',
'VERIFICATION_PROFILE_CHANGED',
'MANIFEST_RESOURCE_POLICY_REQUIRED',
'MANIFEST_BUILD_POLICY_MISMATCH',
'MANIFEST_HEALTH_POLICY_MISMATCH',
'MANIFEST_RESOURCE_LIMIT',
'MANIFEST_SCHEMA',
'MANIFEST_YAML',
'MANIFEST_SIZE',
'MANIFEST_FILE_TYPE',
]);
const CREDENTIALS = new Set(['UNCONFIGURED', 'CREDENTIAL_ENV_POLICY']);
/** Infrastructure faults wait for a person; they never consume a repair round (requirements FR-E5). */
export function waitingFor(error: unknown): ActivityOutcome {
if (error instanceof RuntimeError) {
const reason: WaitingReason = GIT_STORAGE.has(error.code)
? 'git_storage'
: VERIFICATION.has(error.code)
? 'verification_unconfigured'
: CREDENTIALS.has(error.code)
? 'credentials'
: 'infrastructure';
return waiting(reason, `${error.code}: ${error.message}`);
}
return waiting('infrastructure', error instanceof Error ? error.message : 'Execution failed');
}
/**
* When the control plane stopped the run or rejected the lease, report the state it recorded
* instead of guessing. Anything still unexplained is rethrown, so the workflow records an
* ambiguous execution rather than retrying a side effect.
*/
export async function outcomeForError(error: unknown, readRun: () => Promise<Run>): Promise<ActivityOutcome> {
const stoppedByControlPlane =
error instanceof RunStopped ||
error instanceof ControlPlaneError ||
(error instanceof RuntimeError && error.code === 'CANCELED');
if (!stoppedByControlPlane) return waitingFor(error);
const run = await readRun().catch(() => undefined);
const stopped = run && stoppedOutcome(run);
if (stopped) return stopped;
if (run?.status === 'waiting') return { status: 'waiting' };
throw error;
}
export function abortableDelay(ms: number, signal: AbortSignal) {
return new Promise<void>((resolve, reject) => {
if (signal.aborted) return reject(signal.reason);
const timer = setTimeout(resolve, ms);
signal.addEventListener(
'abort',
() => {
clearTimeout(timer);
reject(signal.reason);
},
{ once: true },
);
});
}