@tangle-network/agent-runtime 0.108.0 → 0.109.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{index-BZbJWqoZ.d.ts → index-B6p86EqB.d.ts} +4 -4
- package/dist/{index-cdkwHruJ.d.ts → index-CqWEbmGh.d.ts} +2 -2
- package/dist/{index-DQp3BPeC.d.ts → index-lpqu3wdI.d.ts} +4 -4
- package/dist/index.d.ts +7 -6
- package/dist/index.js +4 -4
- package/dist/{loops.d.ts → kernel.d.ts} +1 -1
- package/dist/{loops.js → kernel.js} +2 -2
- package/dist/{knowledge-rdrpPIXs.js → knowledge-DwVmEJyG.js} +2 -2
- package/dist/{knowledge-rdrpPIXs.js.map → knowledge-DwVmEJyG.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-B1V-XS5A.js → loop-runner-bin-C6gjS2Ar.js} +3 -3
- package/dist/{loop-runner-bin-B1V-XS5A.js.map → loop-runner-bin-C6gjS2Ar.js.map} +1 -1
- package/dist/{loop-runner-bin-9-JlGqN7.d.ts → loop-runner-bin-D55_d9K8.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +3 -3
- package/dist/{openai-tools-BjQq2TTL.js → openai-tools-B17qCuEc.js} +2 -2
- package/dist/{openai-tools-BjQq2TTL.js.map → openai-tools-B17qCuEc.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{runtime-CDekUROm.js → runtime-bCvzR6fc.js} +5 -5
- package/dist/{runtime-CDekUROm.js.map → runtime-bCvzR6fc.js.map} +1 -1
- package/dist/{supervise-JfKPwIlO.js → supervise-DXjtclYS.js} +3 -3
- package/dist/supervise-DXjtclYS.js.map +1 -0
- package/dist/testing.js +7 -7
- package/package.json +8 -8
- package/dist/supervise-JfKPwIlO.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge-rdrpPIXs.js","names":[],"sources":["../src/knowledge/activation.ts","../src/knowledge/supervised-update.ts","../src/knowledge/improvement-job.ts"],"sourcesContent":["import type {\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n fromAgentCandidateKnowledgeRef,\n type KnowledgeImprovementMutationReceipt,\n loadKnowledgeImprovementActivationResult,\n type PromoteKnowledgeCandidateOptions,\n promoteKnowledgeCandidate,\n restoreKnowledgeCandidateBaseline,\n} from '@tangle-network/agent-knowledge'\n\nimport {\n type AgentImprovementActivationReconciliation,\n type AgentImprovementActivationResultStore,\n type AgentImprovementActivationTransition,\n type AgentImprovementActivationTransitionInput,\n createAgentImprovementActivationResult,\n} from '../intelligence/activation'\n\nexport interface CreateKnowledgeImprovementActivationExecutorOptions\n extends Omit<PromoteKnowledgeCandidateOptions, 'root' | 'candidate'> {\n root: string\n identity: string\n results: AgentImprovementActivationResultStore\n}\n\nexport interface KnowledgeImprovementActivationExecutor {\n transition: AgentImprovementActivationTransition\n reconcile: AgentImprovementActivationReconciliation\n}\n\n/** Apply or restore one local knowledge candidate through the shared activation contract. */\nexport function createKnowledgeImprovementActivationExecutor(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n): KnowledgeImprovementActivationExecutor {\n if (!options.identity.trim()) throw new Error('knowledge activation identity is required')\n return {\n reconcile: async (transition) => {\n const inspected = await inspectKnowledgeActivation(options, transition)\n return inspected.settled ? inspected.result : undefined\n },\n transition: async (transition) => {\n if (transition.expired) {\n throw new Error('knowledge write transition cannot run after authorization expires')\n }\n const inspected = await inspectKnowledgeActivation(options, transition)\n if (inspected.settled) return inspected.result\n\n const mutationOptions = {\n root: options.root,\n candidate: inspected.candidate,\n activation: {\n activation: transition.activation,\n attemptedAt: transition.attemptedAt,\n identity: options.identity,\n createResult: (receipt: KnowledgeImprovementMutationReceipt) =>\n inspected.create(\n knowledgeMutationOutcome(receipt, inspected, transition.activation.intent),\n ),\n },\n ...(options.ownerId ? { ownerId: options.ownerId } : {}),\n ...(options.leaseTtlMs === undefined ? {} : { leaseTtlMs: options.leaseTtlMs }),\n ...(options.now ? { now: options.now } : {}),\n ...(options.onState ? { onState: options.onState } : {}),\n }\n const improvement =\n transition.activation.intent === 'activate-candidate'\n ? await promoteKnowledgeCandidate(mutationOptions)\n : await restoreKnowledgeCandidateBaseline(mutationOptions)\n if (!improvement.activationResult) {\n throw new Error('knowledge mutation did not persist its shared activation result')\n }\n return options.results.putIfAbsent(improvement.activationResult)\n },\n }\n}\n\ntype CreateKnowledgeActivation = (\n outcome: AgentImprovementActivationOutcome,\n) => AgentImprovementActivationResult\n\ntype InspectedKnowledgeActivation =\n | { settled: true; result: unknown | undefined }\n | {\n settled: false\n target: AgentImprovementActivationTransitionInput['targets'][number]\n candidate: PromoteKnowledgeCandidateOptions['candidate']\n expectedDigest: Sha256Digest\n desiredDigest: Sha256Digest\n create: CreateKnowledgeActivation\n }\n\nasync function inspectKnowledgeActivation(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n transition: AgentImprovementActivationTransitionInput,\n): Promise<InspectedKnowledgeActivation> {\n const stored = await options.results.load(transition.activation.digest)\n if (stored !== undefined) return { settled: true, result: stored }\n\n const create: CreateKnowledgeActivation = (outcome) =>\n createAgentImprovementActivationResult(transition, {\n completedAt: completionTime(transition, options.now),\n outcome,\n })\n const store = (outcome: AgentImprovementActivationOutcome) =>\n options.results.putIfAbsent(create(outcome))\n if (transition.kind !== 'sealed-candidate') {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_PROFILE_TRANSITION_UNSUPPORTED',\n message: 'The knowledge adapter accepts only sealed knowledge candidates.',\n }),\n }\n }\n const target = supportedKnowledgeTarget(transition, options.identity)\n if (!target) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_TARGET_SET_UNSUPPORTED',\n message: 'The knowledge adapter requires exactly one matching knowledge target.',\n }),\n }\n }\n const knowledge = transition.candidateBundle.knowledge\n if (!knowledge) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_CANDIDATE_MISSING',\n message: 'The measured candidate bundle does not contain a knowledge candidate.',\n }),\n }\n }\n const candidate = fromAgentCandidateKnowledgeRef(knowledge.candidate)\n const expectedDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.baseHash\n : knowledge.candidate.candidateHash\n const desiredDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.candidateHash\n : knowledge.candidate.baseHash\n if (target.expectedBaseDigest !== expectedDigest || target.desiredDigest !== desiredDigest) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'failed',\n code: 'KNOWLEDGE_TARGET_MISMATCH',\n message: 'The activation target does not match the measured knowledge candidate.',\n }),\n }\n }\n\n const durable = await loadKnowledgeImprovementActivationResult({\n root: options.root,\n candidate,\n activation: transition.activation,\n identity: options.identity,\n })\n if (durable) {\n return {\n settled: true,\n result: await options.results.putIfAbsent(durable),\n }\n }\n if (transition.expired) return { settled: true, result: undefined }\n return { settled: false, target, candidate, expectedDigest, desiredDigest, create }\n}\n\nfunction supportedKnowledgeTarget(\n transition: AgentImprovementActivationTransitionInput,\n identity: string,\n): AgentImprovementActivationTransitionInput['targets'][number] | undefined {\n if (transition.targets.length !== 1) return undefined\n const target = transition.targets[0]\n return target.surface === 'knowledge' && target.identity === identity ? target : undefined\n}\n\nfunction knowledgeMutationOutcome(\n receipt: KnowledgeImprovementMutationReceipt,\n inspected: Extract<InspectedKnowledgeActivation, { settled: false }>,\n intent: AgentImprovementActivationTransitionInput['activation']['intent'],\n): AgentImprovementActivationOutcome {\n const expectedTarget = intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const beforeDigest = prefixedDigest(receipt.beforeHash)\n const afterDigest = prefixedDigest(receipt.afterHash)\n if (\n receipt.target !== expectedTarget ||\n receipt.changed !== (beforeDigest !== afterDigest) ||\n (!receipt.changed && (receipt.transactionId !== null || receipt.recovered))\n ) {\n throw new Error('knowledge mutation returned inconsistent state evidence')\n }\n if (receipt.changed) {\n if (\n receipt.transactionId === null ||\n beforeDigest !== inspected.expectedDigest ||\n afterDigest !== inspected.desiredDigest\n ) {\n throw new Error('knowledge activation did not apply its authorized content transition')\n }\n return {\n status: 'applied',\n transactionId: receipt.transactionId,\n targets: [\n {\n surface: inspected.target.surface,\n identity: inspected.target.identity,\n beforeDigest,\n afterDigest,\n },\n ],\n }\n }\n if (afterDigest === inspected.desiredDigest) {\n return {\n status: 'already-applied',\n targets: [targetState(inspected.target, afterDigest)],\n }\n }\n if (afterDigest === inspected.expectedDigest) {\n throw new Error('knowledge activation did not attempt its authorized content transition')\n }\n return {\n status: 'conflict',\n targets: [targetState(inspected.target, afterDigest)],\n }\n}\n\nfunction targetState(target: AgentImprovementActivationTarget, currentDigest: Sha256Digest) {\n return {\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n }\n}\n\nfunction prefixedDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${hash}`)\n}\n\nfunction completionTime(\n transition: AgentImprovementActivationTransitionInput,\n now: (() => Date) | undefined,\n): string {\n const completedAt = (now ?? (() => new Date()))().toISOString()\n return Date.parse(completedAt) < Date.parse(transition.attemptedAt)\n ? transition.attemptedAt\n : completedAt\n}\n","import type { RagKnowledgeUpdateResult } from '@tangle-network/agent-knowledge'\nimport { researcherProfile } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: NonNullable<RagKnowledgeUpdateResult['metadata']>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n harness?: string\n supervisorModel?: string\n supervisorSystemPrompt?: string\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const { profile: workerProfile } = researcherProfile({ harness: options.harness })\n const baseInstructions = options.supervisorSystemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = workerProfile.prompt?.systemPrompt\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n name: 'knowledge-research-supervisor',\n model: options.supervisorModel,\n systemPrompt,\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\\n\\n')}\\n\\nUpdate files under the knowledge base root only. Stop when the readiness check passes.`\n}\n","import { realpath } from 'node:fs/promises'\nimport {\n type AgentCandidateBundle,\n type AgentCandidateCapturedArtifact,\n type AgentCandidateKnowledge,\n agentCandidateKnowledgeSchema,\n} from '@tangle-network/agent-interface'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n knowledgeImprovementCandidateRef,\n toAgentCandidateKnowledgeRef,\n withKnowledgeImprovementComparison,\n} from '@tangle-network/agent-knowledge'\nimport { sealAgentCandidateBundle } from '../candidate-execution/bundle'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { captureAgentCandidateWorkspace } from '../candidate-execution/workspace-archive'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n harness?: string\n supervisorModel?: string\n supervisorSystemPrompt?: string\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n candidateArtifacts?: AgentCandidateOutputArtifactPort\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usdKnown: boolean\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n knowledge?: KnowledgeImprovementCandidatePair\n measurement: KnowledgeImprovementJobMeasurement\n blocked: boolean\n}\n\nexport interface KnowledgeImprovementCandidatePair {\n reference: AgentCandidateKnowledge['candidate']\n evaluation: AgentCandidateCapturedArtifact\n baseline: AgentCandidateKnowledge['snapshot']\n candidate: AgentCandidateKnowledge['snapshot']\n}\n\nexport interface KnowledgeImprovementExperimentBundles {\n baseline: AgentCandidateBundle\n candidate: AgentCandidateBundle\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Produce a frozen KB candidate while leaving live knowledge content unchanged. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n candidateArtifacts,\n harness,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorModel,\n supervisorSystemPrompt,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n harness,\n supervisorModel,\n supervisorSystemPrompt,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const instrumentedUpdateKnowledge: KnowledgeImprovementOptions['updateKnowledge'] = async (\n input,\n ) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n }\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: instrumentedUpdateKnowledge,\n })\n let knowledge: KnowledgeImprovementCandidatePair | undefined\n if (\n resolvedImprovement.candidate?.status === 'candidate-ready' ||\n resolvedImprovement.candidate?.status === 'promoted'\n ) {\n knowledge = await freezeKnowledgeCandidatePair(\n options.root,\n resolvedImprovement,\n candidateArtifacts,\n knowledgeOptions.signal,\n )\n }\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n ...(knowledge ? { knowledge } : {}),\n measurement,\n blocked: resolvedImprovement.blocked,\n }\n}\n\n/** Attach both frozen knowledge inputs to one otherwise-identical bundle pair. */\nexport function buildKnowledgeImprovementExperimentBundles(\n bundle: AgentCandidateBundle,\n knowledge: KnowledgeImprovementCandidatePair,\n): KnowledgeImprovementExperimentBundles {\n const input = omitTopLevelDigest(bundle)\n const withSnapshot = (snapshot: AgentCandidateKnowledge['snapshot']) =>\n agentCandidateKnowledgeSchema.parse({\n candidate: knowledge.reference,\n snapshot,\n evaluation: knowledge.evaluation,\n })\n return Object.freeze({\n baseline: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.baseline) }),\n candidate: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.candidate) }),\n })\n}\n\nasync function freezeKnowledgeCandidatePair(\n root: string,\n improvement: KnowledgeImprovementResult,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<KnowledgeImprovementCandidatePair> {\n const candidate = knowledgeImprovementCandidateRef(improvement)\n const candidateRef = toAgentCandidateKnowledgeRef(candidate)\n return withKnowledgeImprovementComparison({ root, candidate }, async (comparison) => {\n const freeze = async (\n target: 'baseline' | 'candidate',\n ): Promise<AgentCandidateKnowledge['snapshot']> => {\n const executionId = `knowledge-${candidate.candidateId}-${target}`\n const captured = await captureAgentCandidateWorkspace(\n await realpath(comparison[target].root),\n {\n ...(artifacts\n ? {\n artifactPersistence: {\n executionId,\n outputArtifacts: artifacts,\n ...(signal ? { signal } : {}),\n },\n }\n : {}),\n },\n )\n return captured.snapshot\n }\n const evaluation = await captureKnowledgeEvidence(\n canonicalCandidateBytes({\n kind: 'agent-knowledge-candidate-evaluation',\n candidate: candidateRef,\n metric: comparison.evaluation,\n }),\n 'knowledge-evaluation',\n `knowledge-${candidate.candidateId}`,\n artifacts,\n signal,\n )\n const baseline = await freeze('baseline')\n const proposed = await freeze('candidate')\n return Object.freeze({\n reference: candidateRef,\n evaluation,\n baseline,\n candidate: proposed,\n })\n })\n}\n\nasync function captureKnowledgeEvidence(\n bytes: Uint8Array,\n purpose: 'knowledge-evaluation',\n executionId: string,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<AgentCandidateCapturedArtifact> {\n if (!artifacts) return embeddedCandidateArtifact(bytes)\n return persistCandidateOutputArtifact(artifacts, {\n executionId,\n purpose,\n bytes,\n ...(signal ? { signal } : {}),\n })\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usdKnown: true, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations\n target.inputTokens += spent.tokens.input\n target.outputTokens += spent.tokens.output\n target.usdKnown = target.usdKnown && spent.usdKnown !== false\n target.usd += spent.usd\n target.ms += spent.ms\n}\n"],"mappings":";;;;;;;;;;AAqCA,SAAgB,6CACd,SACwC;CACxC,IAAI,CAAC,QAAQ,SAAS,KAAK,GAAG,MAAM,IAAI,MAAM,2CAA2C;CACzF,OAAO;EACL,WAAW,OAAO,eAAe;GAC/B,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,OAAO,UAAU,UAAU,UAAU,SAAS,KAAA;EAChD;EACA,YAAY,OAAO,eAAe;GAChC,IAAI,WAAW,SACb,MAAM,IAAI,MAAM,mEAAmE;GAErF,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,IAAI,UAAU,SAAS,OAAO,UAAU;G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Ac;EAAG,UAAU;EAAM,KAAK;EAAG,IAAI;CAAE;AACzF;AAEA,SAAS,SACP,QACA,QACM;CACN,MAAM,QAAQ,OAAO;CACrB,OAAO,cAAc,MAAM;CAC3B,OAAO,eAAe,MAAM,OAAO;CACnC,OAAO,gBAAgB,MAAM,OAAO;CACpC,OAAO,WAAW,OAAO,YAAY,MAAM,aAAa;CACxD,OAAO,OAAO,MAAM;CACpB,OAAO,MAAM,MAAM;AACrB"}
|
|
1
|
+
{"version":3,"file":"knowledge-DwVmEJyG.js","names":[],"sources":["../src/knowledge/activation.ts","../src/knowledge/supervised-update.ts","../src/knowledge/improvement-job.ts"],"sourcesContent":["import type {\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { sha256DigestSchema } from '@tangle-network/agent-interface'\nimport {\n fromAgentCandidateKnowledgeRef,\n type KnowledgeImprovementMutationReceipt,\n loadKnowledgeImprovementActivationResult,\n type PromoteKnowledgeCandidateOptions,\n promoteKnowledgeCandidate,\n restoreKnowledgeCandidateBaseline,\n} from '@tangle-network/agent-knowledge'\n\nimport {\n type AgentImprovementActivationReconciliation,\n type AgentImprovementActivationResultStore,\n type AgentImprovementActivationTransition,\n type AgentImprovementActivationTransitionInput,\n createAgentImprovementActivationResult,\n} from '../intelligence/activation'\n\nexport interface CreateKnowledgeImprovementActivationExecutorOptions\n extends Omit<PromoteKnowledgeCandidateOptions, 'root' | 'candidate'> {\n root: string\n identity: string\n results: AgentImprovementActivationResultStore\n}\n\nexport interface KnowledgeImprovementActivationExecutor {\n transition: AgentImprovementActivationTransition\n reconcile: AgentImprovementActivationReconciliation\n}\n\n/** Apply or restore one local knowledge candidate through the shared activation contract. */\nexport function createKnowledgeImprovementActivationExecutor(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n): KnowledgeImprovementActivationExecutor {\n if (!options.identity.trim()) throw new Error('knowledge activation identity is required')\n return {\n reconcile: async (transition) => {\n const inspected = await inspectKnowledgeActivation(options, transition)\n return inspected.settled ? inspected.result : undefined\n },\n transition: async (transition) => {\n if (transition.expired) {\n throw new Error('knowledge write transition cannot run after authorization expires')\n }\n const inspected = await inspectKnowledgeActivation(options, transition)\n if (inspected.settled) return inspected.result\n\n const mutationOptions = {\n root: options.root,\n candidate: inspected.candidate,\n activation: {\n activation: transition.activation,\n attemptedAt: transition.attemptedAt,\n identity: options.identity,\n createResult: (receipt: KnowledgeImprovementMutationReceipt) =>\n inspected.create(\n knowledgeMutationOutcome(receipt, inspected, transition.activation.intent),\n ),\n },\n ...(options.ownerId ? { ownerId: options.ownerId } : {}),\n ...(options.leaseTtlMs === undefined ? {} : { leaseTtlMs: options.leaseTtlMs }),\n ...(options.now ? { now: options.now } : {}),\n ...(options.onState ? { onState: options.onState } : {}),\n }\n const improvement =\n transition.activation.intent === 'activate-candidate'\n ? await promoteKnowledgeCandidate(mutationOptions)\n : await restoreKnowledgeCandidateBaseline(mutationOptions)\n if (!improvement.activationResult) {\n throw new Error('knowledge mutation did not persist its shared activation result')\n }\n return options.results.putIfAbsent(improvement.activationResult)\n },\n }\n}\n\ntype CreateKnowledgeActivation = (\n outcome: AgentImprovementActivationOutcome,\n) => AgentImprovementActivationResult\n\ntype InspectedKnowledgeActivation =\n | { settled: true; result: unknown | undefined }\n | {\n settled: false\n target: AgentImprovementActivationTransitionInput['targets'][number]\n candidate: PromoteKnowledgeCandidateOptions['candidate']\n expectedDigest: Sha256Digest\n desiredDigest: Sha256Digest\n create: CreateKnowledgeActivation\n }\n\nasync function inspectKnowledgeActivation(\n options: CreateKnowledgeImprovementActivationExecutorOptions,\n transition: AgentImprovementActivationTransitionInput,\n): Promise<InspectedKnowledgeActivation> {\n const stored = await options.results.load(transition.activation.digest)\n if (stored !== undefined) return { settled: true, result: stored }\n\n const create: CreateKnowledgeActivation = (outcome) =>\n createAgentImprovementActivationResult(transition, {\n completedAt: completionTime(transition, options.now),\n outcome,\n })\n const store = (outcome: AgentImprovementActivationOutcome) =>\n options.results.putIfAbsent(create(outcome))\n if (transition.kind !== 'sealed-candidate') {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_PROFILE_TRANSITION_UNSUPPORTED',\n message: 'The knowledge adapter accepts only sealed knowledge candidates.',\n }),\n }\n }\n const target = supportedKnowledgeTarget(transition, options.identity)\n if (!target) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_TARGET_SET_UNSUPPORTED',\n message: 'The knowledge adapter requires exactly one matching knowledge target.',\n }),\n }\n }\n const knowledge = transition.candidateBundle.knowledge\n if (!knowledge) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'unsupported',\n code: 'KNOWLEDGE_CANDIDATE_MISSING',\n message: 'The measured candidate bundle does not contain a knowledge candidate.',\n }),\n }\n }\n const candidate = fromAgentCandidateKnowledgeRef(knowledge.candidate)\n const expectedDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.baseHash\n : knowledge.candidate.candidateHash\n const desiredDigest =\n transition.activation.intent === 'activate-candidate'\n ? knowledge.candidate.candidateHash\n : knowledge.candidate.baseHash\n if (target.expectedBaseDigest !== expectedDigest || target.desiredDigest !== desiredDigest) {\n if (transition.expired) return { settled: true, result: undefined }\n return {\n settled: true,\n result: await store({\n status: 'failed',\n code: 'KNOWLEDGE_TARGET_MISMATCH',\n message: 'The activation target does not match the measured knowledge candidate.',\n }),\n }\n }\n\n const durable = await loadKnowledgeImprovementActivationResult({\n root: options.root,\n candidate,\n activation: transition.activation,\n identity: options.identity,\n })\n if (durable) {\n return {\n settled: true,\n result: await options.results.putIfAbsent(durable),\n }\n }\n if (transition.expired) return { settled: true, result: undefined }\n return { settled: false, target, candidate, expectedDigest, desiredDigest, create }\n}\n\nfunction supportedKnowledgeTarget(\n transition: AgentImprovementActivationTransitionInput,\n identity: string,\n): AgentImprovementActivationTransitionInput['targets'][number] | undefined {\n if (transition.targets.length !== 1) return undefined\n const target = transition.targets[0]\n return target.surface === 'knowledge' && target.identity === identity ? target : undefined\n}\n\nfunction knowledgeMutationOutcome(\n receipt: KnowledgeImprovementMutationReceipt,\n inspected: Extract<InspectedKnowledgeActivation, { settled: false }>,\n intent: AgentImprovementActivationTransitionInput['activation']['intent'],\n): AgentImprovementActivationOutcome {\n const expectedTarget = intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const beforeDigest = prefixedDigest(receipt.beforeHash)\n const afterDigest = prefixedDigest(receipt.afterHash)\n if (\n receipt.target !== expectedTarget ||\n receipt.changed !== (beforeDigest !== afterDigest) ||\n (!receipt.changed && (receipt.transactionId !== null || receipt.recovered))\n ) {\n throw new Error('knowledge mutation returned inconsistent state evidence')\n }\n if (receipt.changed) {\n if (\n receipt.transactionId === null ||\n beforeDigest !== inspected.expectedDigest ||\n afterDigest !== inspected.desiredDigest\n ) {\n throw new Error('knowledge activation did not apply its authorized content transition')\n }\n return {\n status: 'applied',\n transactionId: receipt.transactionId,\n targets: [\n {\n surface: inspected.target.surface,\n identity: inspected.target.identity,\n beforeDigest,\n afterDigest,\n },\n ],\n }\n }\n if (afterDigest === inspected.desiredDigest) {\n return {\n status: 'already-applied',\n targets: [targetState(inspected.target, afterDigest)],\n }\n }\n if (afterDigest === inspected.expectedDigest) {\n throw new Error('knowledge activation did not attempt its authorized content transition')\n }\n return {\n status: 'conflict',\n targets: [targetState(inspected.target, afterDigest)],\n }\n}\n\nfunction targetState(target: AgentImprovementActivationTarget, currentDigest: Sha256Digest) {\n return {\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n }\n}\n\nfunction prefixedDigest(hash: string): Sha256Digest {\n return sha256DigestSchema.parse(`sha256:${hash}`)\n}\n\nfunction completionTime(\n transition: AgentImprovementActivationTransitionInput,\n now: (() => Date) | undefined,\n): string {\n const completedAt = (now ?? (() => new Date()))().toISOString()\n return Date.parse(completedAt) < Date.parse(transition.attemptedAt)\n ? transition.attemptedAt\n : completedAt\n}\n","import type { RagKnowledgeUpdateResult } from '@tangle-network/agent-knowledge'\nimport { researcherProfile } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: NonNullable<RagKnowledgeUpdateResult['metadata']>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n harness?: string\n supervisorModel?: string\n supervisorSystemPrompt?: string\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const { profile: workerProfile } = researcherProfile({ harness: options.harness })\n const baseInstructions = options.supervisorSystemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = workerProfile.prompt?.systemPrompt\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n name: 'knowledge-research-supervisor',\n model: options.supervisorModel,\n systemPrompt,\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\\n\\n')}\\n\\nUpdate files under the knowledge base root only. Stop when the readiness check passes.`\n}\n","import { realpath } from 'node:fs/promises'\nimport {\n type AgentCandidateBundle,\n type AgentCandidateCapturedArtifact,\n type AgentCandidateKnowledge,\n agentCandidateKnowledgeSchema,\n} from '@tangle-network/agent-interface'\nimport {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n knowledgeImprovementCandidateRef,\n toAgentCandidateKnowledgeRef,\n withKnowledgeImprovementComparison,\n} from '@tangle-network/agent-knowledge'\nimport { sealAgentCandidateBundle } from '../candidate-execution/bundle'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n} from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { captureAgentCandidateWorkspace } from '../candidate-execution/workspace-archive'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n harness?: string\n supervisorModel?: string\n supervisorSystemPrompt?: string\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n candidateArtifacts?: AgentCandidateOutputArtifactPort\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usdKnown: boolean\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n knowledge?: KnowledgeImprovementCandidatePair\n measurement: KnowledgeImprovementJobMeasurement\n blocked: boolean\n}\n\nexport interface KnowledgeImprovementCandidatePair {\n reference: AgentCandidateKnowledge['candidate']\n evaluation: AgentCandidateCapturedArtifact\n baseline: AgentCandidateKnowledge['snapshot']\n candidate: AgentCandidateKnowledge['snapshot']\n}\n\nexport interface KnowledgeImprovementExperimentBundles {\n baseline: AgentCandidateBundle\n candidate: AgentCandidateBundle\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Produce a frozen KB candidate while leaving live knowledge content unchanged. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n candidateArtifacts,\n harness,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorModel,\n supervisorSystemPrompt,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n harness,\n supervisorModel,\n supervisorSystemPrompt,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const instrumentedUpdateKnowledge: KnowledgeImprovementOptions['updateKnowledge'] = async (\n input,\n ) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n }\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: instrumentedUpdateKnowledge,\n })\n let knowledge: KnowledgeImprovementCandidatePair | undefined\n if (\n resolvedImprovement.candidate?.status === 'candidate-ready' ||\n resolvedImprovement.candidate?.status === 'promoted'\n ) {\n knowledge = await freezeKnowledgeCandidatePair(\n options.root,\n resolvedImprovement,\n candidateArtifacts,\n knowledgeOptions.signal,\n )\n }\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n ...(knowledge ? { knowledge } : {}),\n measurement,\n blocked: resolvedImprovement.blocked,\n }\n}\n\n/** Attach both frozen knowledge inputs to one otherwise-identical bundle pair. */\nexport function buildKnowledgeImprovementExperimentBundles(\n bundle: AgentCandidateBundle,\n knowledge: KnowledgeImprovementCandidatePair,\n): KnowledgeImprovementExperimentBundles {\n const input = omitTopLevelDigest(bundle)\n const withSnapshot = (snapshot: AgentCandidateKnowledge['snapshot']) =>\n agentCandidateKnowledgeSchema.parse({\n candidate: knowledge.reference,\n snapshot,\n evaluation: knowledge.evaluation,\n })\n return Object.freeze({\n baseline: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.baseline) }),\n candidate: sealAgentCandidateBundle({ ...input, knowledge: withSnapshot(knowledge.candidate) }),\n })\n}\n\nasync function freezeKnowledgeCandidatePair(\n root: string,\n improvement: KnowledgeImprovementResult,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<KnowledgeImprovementCandidatePair> {\n const candidate = knowledgeImprovementCandidateRef(improvement)\n const candidateRef = toAgentCandidateKnowledgeRef(candidate)\n return withKnowledgeImprovementComparison({ root, candidate }, async (comparison) => {\n const freeze = async (\n target: 'baseline' | 'candidate',\n ): Promise<AgentCandidateKnowledge['snapshot']> => {\n const executionId = `knowledge-${candidate.candidateId}-${target}`\n const captured = await captureAgentCandidateWorkspace(\n await realpath(comparison[target].root),\n {\n ...(artifacts\n ? {\n artifactPersistence: {\n executionId,\n outputArtifacts: artifacts,\n ...(signal ? { signal } : {}),\n },\n }\n : {}),\n },\n )\n return captured.snapshot\n }\n const evaluation = await captureKnowledgeEvidence(\n canonicalCandidateBytes({\n kind: 'agent-knowledge-candidate-evaluation',\n candidate: candidateRef,\n metric: comparison.evaluation,\n }),\n 'knowledge-evaluation',\n `knowledge-${candidate.candidateId}`,\n artifacts,\n signal,\n )\n const baseline = await freeze('baseline')\n const proposed = await freeze('candidate')\n return Object.freeze({\n reference: candidateRef,\n evaluation,\n baseline,\n candidate: proposed,\n })\n })\n}\n\nasync function captureKnowledgeEvidence(\n bytes: Uint8Array,\n purpose: 'knowledge-evaluation',\n executionId: string,\n artifacts: AgentCandidateOutputArtifactPort | undefined,\n signal: AbortSignal | undefined,\n): Promise<AgentCandidateCapturedArtifact> {\n if (!artifacts) return embeddedCandidateArtifact(bytes)\n return persistCandidateOutputArtifact(artifacts, {\n executionId,\n purpose,\n bytes,\n ...(signal ? { signal } : {}),\n })\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usdKnown: true, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations\n target.inputTokens += spent.tokens.input\n target.outputTokens += spent.tokens.output\n target.usdKnown = target.usdKnown && spent.usdKnown !== false\n target.usd += spent.usd\n target.ms += spent.ms\n}\n"],"mappings":";;;;;;;;;;AAqCA,SAAgB,6CACd,SACwC;CACxC,IAAI,CAAC,QAAQ,SAAS,KAAK,GAAG,MAAM,IAAI,MAAM,2CAA2C;CACzF,OAAO;EACL,WAAW,OAAO,eAAe;GAC/B,MAAM,YAAY,MAAM,2BAA2B,SAAS,UAAU;GACtE,OAAO,UAAU,UAAU,UAAU,SAA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;CACtD,OAAO,+BAA+B,WAAW;EAC/C;EACA;EACA;EACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAC7B,CAAC;AACH;AAEA,SAAS,aAAoE;CAC3E,OAAO;EAAE,YAAY;EAAG,aAAa;EAAG,cAAc;EAAG,UAAU;EAAM,KAAK;EAAG,IAAI;CAAE;AACzF;AAEA,SAAS,SACP,QACA,QACM;CACN,MAAM,QAAQ,OAAO;CACrB,OAAO,cAAc,MAAM;CAC3B,OAAO,eAAe,MAAM,OAAO;CACnC,OAAO,gBAAgB,MAAM,OAAO;CACpC,OAAO,WAAW,OAAO,YAAY,MAAM,aAAa;CACxD,OAAO,OAAO,MAAM;CACpB,OAAO,MAAM,MAAM;AACrB"}
|
package/dist/knowledge.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as KnowledgeImprovementActivationExecutor, S as CreateKnowledgeImprovementActivationExecutorOptions, _ as SupervisedKnowledgeUpdater, a as KnowledgeImprovementJobResult, b as knowledgeReadinessDeliverable, c as createAgentKnowledgeReadinessCheck, d as KnowledgeReadinessCheckInput, f as KnowledgeReadinessCheckResult, g as SupervisedKnowledgeUpdateResult, h as SupervisedKnowledgeUpdateOptions, i as KnowledgeImprovementJobMeasurement, l as runKnowledgeImprovementJob, m as SupervisedKnowledgeUpdateInput, n as KnowledgeImprovementCandidatePair, o as RunKnowledgeImprovementJobOptions, p as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, r as KnowledgeImprovementExperimentBundles, s as buildKnowledgeImprovementExperimentBundles, t as AgentKnowledgeReadinessCheckOptions, u as KnowledgeReadinessCheck, v as createSupervisedKnowledgeUpdater, w as createKnowledgeImprovementActivationExecutor, x as runSupervisedKnowledgeUpdate, y as formatSupervisedKnowledgeTask } from "./index-
|
|
1
|
+
import { C as KnowledgeImprovementActivationExecutor, S as CreateKnowledgeImprovementActivationExecutorOptions, _ as SupervisedKnowledgeUpdater, a as KnowledgeImprovementJobResult, b as knowledgeReadinessDeliverable, c as createAgentKnowledgeReadinessCheck, d as KnowledgeReadinessCheckInput, f as KnowledgeReadinessCheckResult, g as SupervisedKnowledgeUpdateResult, h as SupervisedKnowledgeUpdateOptions, i as KnowledgeImprovementJobMeasurement, l as runKnowledgeImprovementJob, m as SupervisedKnowledgeUpdateInput, n as KnowledgeImprovementCandidatePair, o as RunKnowledgeImprovementJobOptions, p as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, r as KnowledgeImprovementExperimentBundles, s as buildKnowledgeImprovementExperimentBundles, t as AgentKnowledgeReadinessCheckOptions, u as KnowledgeReadinessCheck, v as createSupervisedKnowledgeUpdater, w as createKnowledgeImprovementActivationExecutor, x as runSupervisedKnowledgeUpdate, y as formatSupervisedKnowledgeTask } from "./index-CqWEbmGh.js";
|
|
2
2
|
export { type AgentKnowledgeReadinessCheckOptions, type CreateKnowledgeImprovementActivationExecutorOptions, type KnowledgeImprovementActivationExecutor, type KnowledgeImprovementCandidatePair, type KnowledgeImprovementExperimentBundles, type KnowledgeImprovementJobMeasurement, type KnowledgeImprovementJobResult, type KnowledgeReadinessCheck, type KnowledgeReadinessCheckInput, type KnowledgeReadinessCheckResult, RESEARCH_SUPERVISOR_SYSTEM_PROMPT, type RunKnowledgeImprovementJobOptions, type SupervisedKnowledgeUpdateInput, type SupervisedKnowledgeUpdateOptions, type SupervisedKnowledgeUpdateResult, type SupervisedKnowledgeUpdater, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate };
|
package/dist/knowledge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-
|
|
1
|
+
import { a as createSupervisedKnowledgeUpdater, c as runSupervisedKnowledgeUpdate, i as RESEARCH_SUPERVISOR_SYSTEM_PROMPT, l as createKnowledgeImprovementActivationExecutor, n as createAgentKnowledgeReadinessCheck, o as formatSupervisedKnowledgeTask, r as runKnowledgeImprovementJob, s as knowledgeReadinessDeliverable, t as buildKnowledgeImprovementExperimentBundles } from "./knowledge-DwVmEJyG.js";
|
|
2
2
|
export { RESEARCH_SUPERVISOR_SYSTEM_PROMPT, buildKnowledgeImprovementExperimentBundles, createAgentKnowledgeReadinessCheck, createKnowledgeImprovementActivationExecutor, createSupervisedKnowledgeUpdater, formatSupervisedKnowledgeTask, knowledgeReadinessDeliverable, runKnowledgeImprovementJob, runSupervisedKnowledgeUpdate };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as ConfigError } from "./errors-DEAvWQPy.js";
|
|
2
|
-
import { M as runPersonified, d as worktreeFanout, j as definePersona } from "./runtime-
|
|
2
|
+
import { M as runPersonified, d as worktreeFanout, j as definePersona } from "./runtime-bCvzR6fc.js";
|
|
3
3
|
import { t as runAnalystLoop } from "./analyst-loop-C8cGThTW.js";
|
|
4
|
-
import { Dt as createExecutorRegistry } from "./supervise-
|
|
4
|
+
import { Dt as createExecutorRegistry } from "./supervise-DXjtclYS.js";
|
|
5
5
|
import { t as createKbGate } from "./kb-gate-DpaSwXVx.js";
|
|
6
6
|
//#region src/loop-runner.ts
|
|
7
7
|
/**
|
|
@@ -265,4 +265,4 @@ if (invokedScript && /loop-runner-bin\.(js|ts|mjs)$/.test(invokedScript)) main()
|
|
|
265
265
|
//#endregion
|
|
266
266
|
export { isDelegatedLoopMode as a, worktreeLoopRunner as c, auditLoopRunner as i, runLoopRunnerCli as n, researchLoopRunner as o, DELEGATED_LOOP_MODES as r, runDelegatedLoop as s, parseLoopRunnerArgv as t };
|
|
267
267
|
|
|
268
|
-
//# sourceMappingURL=loop-runner-bin-
|
|
268
|
+
//# sourceMappingURL=loop-runner-bin-C6gjS2Ar.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop-runner-bin-B1V-XS5A.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;;;;;;;;;;AA4CA,SAAgB,mBACd,SAC4C;CAC5C,MAAM,QAAQ,eAAuB;EACnC,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;EACpE,GAAI,QAAQ,iBAAiB,KAAA,IAAY,EAAE,cAAc,QAAQ,aAAa,IAAI,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,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
1
|
+
{"version":3,"file":"loop-runner-bin-C6gjS2Ar.js","names":[],"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\n void main()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;;;;;;;;;;AA4CA,SAAgB,mBACd,SAC4C;CAC5C,MAAM,QAAQ,eAAuB;EACnC,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC;EACpE,GAAI,QAAQ,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AC,EAAE,GAAG;CACvF,IAAI,IAAI,OAAO,QAAQ,OAAO,MAAM,GAAG,IAAI,MAAM,GAAG;CACpD,QAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,MAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAK,KAAA;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GACrE,KAAU"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { d as RunAnalystLoopOpts, f as RunAnalystLoopResult } from "./types-CfGKhIuj.js";
|
|
2
2
|
import { R as Budget } from "./environment-provider-D0NXc4Qz.js";
|
|
3
|
-
import { E as WorktreeFanoutOptions, G as WorktreePatchArtifact, T as AuthoredHarness, mo as WinnerStrategy } from "./index-
|
|
3
|
+
import { E as WorktreeFanoutOptions, G as WorktreePatchArtifact, T as AuthoredHarness, mo as WinnerStrategy } from "./index-B6p86EqB.js";
|
|
4
4
|
import { n as FactCandidate, t as CreateKbGateOptions } from "./kb-gate-C8z2juK8.js";
|
|
5
5
|
//#region src/loop-runner.d.ts
|
|
6
6
|
/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */
|
|
@@ -159,4 +159,4 @@ declare function parseLoopRunnerArgv(argv: string[]): {
|
|
|
159
159
|
};
|
|
160
160
|
//#endregion
|
|
161
161
|
export { researchLoopRunner as _, DELEGATED_LOOP_MODES as a, DelegatedLoopResult as c, ResearchLoopRunnerOptions as d, RunDelegatedLoopOptions as f, isDelegatedLoopMode as g, auditLoopRunner as h, runLoopRunnerCli as i, DelegatedLoopRunner as l, WorktreeLoopRunnerOptions as m, LoopRunnerCliResult as n, DelegatedLoopMode as o, VetoedFact as p, parseLoopRunnerArgv as r, DelegatedLoopRegistry as s, LoopRunnerCliArgs as t, ResearchLoopResult as u, runDelegatedLoop as v, worktreeLoopRunner as y };
|
|
162
|
-
//# sourceMappingURL=loop-runner-bin-
|
|
162
|
+
//# sourceMappingURL=loop-runner-bin-D55_d9K8.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-
|
|
1
|
+
import { i as runLoopRunnerCli, n as LoopRunnerCliResult, r as parseLoopRunnerArgv, t as LoopRunnerCliArgs } from "./loop-runner-bin-D55_d9K8.js";
|
|
2
2
|
export { LoopRunnerCliArgs, LoopRunnerCliResult, parseLoopRunnerArgv, runLoopRunnerCli };
|
package/dist/loop-runner-bin.js
CHANGED
package/dist/mcp/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { B as DelegationTaskQueue, X as FileDelegationStore, o as createMcpServer } from "../supervise-
|
|
2
|
+
import { B as DelegationTaskQueue, X as FileDelegationStore, o as createMcpServer } from "../supervise-DXjtclYS.js";
|
|
3
3
|
import { a as resolveRouterBaseUrl } from "../model-resolution-Btd9iIKV.js";
|
|
4
4
|
import { n as readTraceContextFromEnv } from "../trace-propagation-CJJC7SVB.js";
|
|
5
5
|
//#region src/mcp/delegate-supervisor-provisioning.ts
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as SandboxClient, h as LoopSandboxPlacement } from "../types-BevOjfTY.js";
|
|
2
|
-
import { $c as DetachedWinnerSelection, $l as DelegationStatus, $s as createDelegateHandler, Ac as DiffOptions, Al as SubmitInput, As as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Au as DELEGATION_TRACE_MAX_BYTES, Bc as JsonRpcMessage, Bl as DelegateResearchResult, Bs as SettledWorker, Bu as DelegationStateCorruptError, Cl as DelegationRecord, Dl as DelegationRunContext, Ds as CoordinationEvent, El as DelegationResumeTick, Es as AnalystRegistry, Fc as captureWorktreeDiff, Fl as DelegateCodeResult, Fs as QuestionLevel, Fu as buildDelegationTraceSpans, Gc as FeedbackStore, Gl as DelegationError, Gs as createInProcessTransport, Hc as McpToolDescriptor, Hl as DelegateUiAuditConfig, Hs as createCoordinationTools, Hu as FileDelegationStore, Ic as createWorktree, Il as DelegateFeedbackArgs, Is as QuestionOption, Iu as capDelegationTrace, Jc as CoderDelegate, Jl as DelegationHistoryEntry, Js as DELEGATE_INPUT_SCHEMA, Kc as InMemoryFeedbackStore, Kl as DelegationFeedbackSnapshot, Ks as createMcpServer, Lc as removeWorktree, Ll as DelegateFeedbackResult, Ls as QuestionPolicy, Lu as composeLoopTraceEmitters, Mc as GitRunner, Ml as hashIdempotencyInput, Ms as MakeWorkerAgent, Mu as DelegationTraceCaps, Nc as RemoveWorktreeOptions, Nl as DelegateCodeArgs, Ns as Question, Nu as DelegationTraceCollector, Ol as DelegationTaskQueue, Os as CoordinationTools, Pc as WorktreeHandle, Pl as DelegateCodeConfig, Ps as QuestionDecision, Pu as DelegationTraceSpan, Qc as DetachedSessionDelegateOptions, Ql as DelegationResultPayload, Qs as DelegateResult, Rl as DelegateResearchArgs, Rs as QuestionRecord, Ru as createDelegationTraceCollector, Sl as DelegationArgs, Tl as DelegationResumeDriver, Ts as AnalystFindingEvent, Uc as McpTransport, Ul as DelegateUiAuditResult, Us as McpServer, Uu as FileDelegationStoreOptions, Vc as JsonRpcResponse, Vl as DelegateUiAuditArgs, Vs as WorkerWatchOptions, Vu as DelegationStore, Wc as FeedbackEvent, Wl as DelegateUiAuditRoute, Ws as McpServerOptions, Wu as InMemoryDelegationStore, Xc as CoderReviewer, Xl as DelegationProfile, Xs as DelegateArgs, Yc as CoderReview, Yl as DelegationHistoryResult, Ys as DELEGATE_TOOL_NAME, Zc as DelegateRunCtx, Zl as DelegationProgress, Zs as DelegateHandlerOptions, _l as createDetachedTurnResumeDriver, al as DelegationExecutor, au as ResearchSource, bl as parseDetachedSessionRef, cl as SiblingSandboxExecutorOptions, cu as TraceContext, dl as DetachedSessionRefParts, du as traceContextToEnv, ec as validateDelegateArgs, ed as CoderOutput, el as SettleDetachedCoderTurnOptions, eu as DelegationStatusArgs, fl as DetachedTurn, gl as RunDetachedTurnOptions, hl as DriveTurnTick, il as settleDetachedCoderTurn, iu as ResearchOutputShape, jc as DiffResult, jl as SubmitOutput, js as DownMessageEvent, ju as DELEGATION_TRACE_MAX_SPANS, kc as CreateWorktreeOptions, kl as DelegationTaskQueueOptions, ks as CoordinationToolsOptions, ku as CappedDelegationTrace, ll as createFleetWorkspaceExecutor, lu as createPropagatingTraceEmitter, ml as DriveTurnCapableBox, nl as coderTaskFromArgs, nu as FeedbackRating, ol as FleetHandle, ou as UiAuditLensFilter, pl as DetachedTurnResumeDriverOptions, qc as eventToSnapshot, ql as DelegationHistoryArgs, qs as DELEGATE_DESCRIPTION, rl as detachedSessionDelegate, ru as FeedbackRefersTo, sl as FleetWorkspaceExecutorOptions, su as UiAuditorDelegationOutput, tl as UiAuditorDelegate, tu as DelegationStatusResult, ul as createSiblingSandboxExecutor, uu as readTraceContextFromEnv, vl as detachedTurnEvents, wl as DelegationResumeContext, xl as runDetachedTurn, yl as formatDetachedSessionRef, zl as DelegateResearchConfig, zs as QuestionUrgency, zu as DelegationPersistenceError } from "../index-
|
|
2
|
+
import { $c as DetachedWinnerSelection, $l as DelegationStatus, $s as createDelegateHandler, Ac as DiffOptions, Al as SubmitInput, As as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Au as DELEGATION_TRACE_MAX_BYTES, Bc as JsonRpcMessage, Bl as DelegateResearchResult, Bs as SettledWorker, Bu as DelegationStateCorruptError, Cl as DelegationRecord, Dl as DelegationRunContext, Ds as CoordinationEvent, El as DelegationResumeTick, Es as AnalystRegistry, Fc as captureWorktreeDiff, Fl as DelegateCodeResult, Fs as QuestionLevel, Fu as buildDelegationTraceSpans, Gc as FeedbackStore, Gl as DelegationError, Gs as createInProcessTransport, Hc as McpToolDescriptor, Hl as DelegateUiAuditConfig, Hs as createCoordinationTools, Hu as FileDelegationStore, Ic as createWorktree, Il as DelegateFeedbackArgs, Is as QuestionOption, Iu as capDelegationTrace, Jc as CoderDelegate, Jl as DelegationHistoryEntry, Js as DELEGATE_INPUT_SCHEMA, Kc as InMemoryFeedbackStore, Kl as DelegationFeedbackSnapshot, Ks as createMcpServer, Lc as removeWorktree, Ll as DelegateFeedbackResult, Ls as QuestionPolicy, Lu as composeLoopTraceEmitters, Mc as GitRunner, Ml as hashIdempotencyInput, Ms as MakeWorkerAgent, Mu as DelegationTraceCaps, Nc as RemoveWorktreeOptions, Nl as DelegateCodeArgs, Ns as Question, Nu as DelegationTraceCollector, Ol as DelegationTaskQueue, Os as CoordinationTools, Pc as WorktreeHandle, Pl as DelegateCodeConfig, Ps as QuestionDecision, Pu as DelegationTraceSpan, Qc as DetachedSessionDelegateOptions, Ql as DelegationResultPayload, Qs as DelegateResult, Rl as DelegateResearchArgs, Rs as QuestionRecord, Ru as createDelegationTraceCollector, Sl as DelegationArgs, Tl as DelegationResumeDriver, Ts as AnalystFindingEvent, Uc as McpTransport, Ul as DelegateUiAuditResult, Us as McpServer, Uu as FileDelegationStoreOptions, Vc as JsonRpcResponse, Vl as DelegateUiAuditArgs, Vs as WorkerWatchOptions, Vu as DelegationStore, Wc as FeedbackEvent, Wl as DelegateUiAuditRoute, Ws as McpServerOptions, Wu as InMemoryDelegationStore, Xc as CoderReviewer, Xl as DelegationProfile, Xs as DelegateArgs, Yc as CoderReview, Yl as DelegationHistoryResult, Ys as DELEGATE_TOOL_NAME, Zc as DelegateRunCtx, Zl as DelegationProgress, Zs as DelegateHandlerOptions, _l as createDetachedTurnResumeDriver, al as DelegationExecutor, au as ResearchSource, bl as parseDetachedSessionRef, cl as SiblingSandboxExecutorOptions, cu as TraceContext, dl as DetachedSessionRefParts, du as traceContextToEnv, ec as validateDelegateArgs, ed as CoderOutput, el as SettleDetachedCoderTurnOptions, eu as DelegationStatusArgs, fl as DetachedTurn, gl as RunDetachedTurnOptions, hl as DriveTurnTick, il as settleDetachedCoderTurn, iu as ResearchOutputShape, jc as DiffResult, jl as SubmitOutput, js as DownMessageEvent, ju as DELEGATION_TRACE_MAX_SPANS, kc as CreateWorktreeOptions, kl as DelegationTaskQueueOptions, ks as CoordinationToolsOptions, ku as CappedDelegationTrace, ll as createFleetWorkspaceExecutor, lu as createPropagatingTraceEmitter, ml as DriveTurnCapableBox, nl as coderTaskFromArgs, nu as FeedbackRating, ol as FleetHandle, ou as UiAuditLensFilter, pl as DetachedTurnResumeDriverOptions, qc as eventToSnapshot, ql as DelegationHistoryArgs, qs as DELEGATE_DESCRIPTION, rl as detachedSessionDelegate, ru as FeedbackRefersTo, sl as FleetWorkspaceExecutorOptions, su as UiAuditorDelegationOutput, tl as UiAuditorDelegate, tu as DelegationStatusResult, ul as createSiblingSandboxExecutor, uu as readTraceContextFromEnv, vl as detachedTurnEvents, wl as DelegationResumeContext, xl as runDetachedTurn, yl as formatDetachedSessionRef, zl as DelegateResearchConfig, zs as QuestionUrgency, zu as DelegationPersistenceError } from "../index-B6p86EqB.js";
|
|
3
3
|
import { o as UiLens } from "../substrate-BcnuSHXm.js";
|
|
4
4
|
import { a as LocalHarnessResult, c as runLocalHarness, i as LocalHarness, n as CodexExecutionPolicy, o as RunLocalHarnessOptions, r as CodexTokenUsage, s as parseCodexTokenUsage, t as CodexExecutionEvidence } from "../local-harness-Dh8PJ0ot.js";
|
|
5
5
|
import { a as KbGateResult, i as FactJudgeVerdict, n as FactCandidate, o as createKbGate, r as FactJudge, t as CreateKbGateOptions } from "../kb-gate-C8z2juK8.js";
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { u as ValidationError } from "../errors-DEAvWQPy.js";
|
|
2
2
|
import { l as throwAbort, n as deleteBoxSafe, s as sleep, u as throwIfAborted } from "../util-MVgdwuIS.js";
|
|
3
3
|
import { F as removeWorktree, L as parseCodexTokenUsage, M as runWorktreeHarness, N as captureWorktreeDiff, P as createWorktree, R as runLocalHarness, z as CodexExecutionDiagnosticError } from "../supervisor-B2LzaWRb.js";
|
|
4
|
-
import { W as selectValidWinner, m as runCoderChecks, q as assertTraceDerivedFindings } from "../runtime-
|
|
5
|
-
import { $ as eventToSnapshot, A as createDelegateHandler, B as DelegationTaskQueue, Bt as runAgentRounds, C as DELEGATE_FEEDBACK_INPUT_SCHEMA, D as DELEGATE_DESCRIPTION, E as validateDelegateFeedbackArgs, G as capDelegationTrace, H as DELEGATION_TRACE_MAX_BYTES, J as DelegationPersistenceError, K as composeLoopTraceEmitters, O as DELEGATE_INPUT_SCHEMA, Q as InMemoryFeedbackStore, Rt as createSandboxForSpec, S as DELEGATE_FEEDBACK_DESCRIPTION, T as createDelegateFeedbackHandler, U as DELEGATION_TRACE_MAX_SPANS, V as hashIdempotencyInput, W as buildDelegationTraceSpans, X as FileDelegationStore, Y as DelegationStateCorruptError, Z as InMemoryDelegationStore, _ as DELEGATE_UI_AUDIT_DESCRIPTION, a as createInProcessTransport, b as createDelegateUiAuditHandler, c as DELEGATION_STATUS_INPUT_SCHEMA, d as validateDelegationStatusArgs, f as DELEGATION_HISTORY_DESCRIPTION, g as validateDelegationHistoryArgs, h as createDelegationHistoryHandler, ht as createCoordinationTools, j as validateDelegateArgs, k as DELEGATE_TOOL_NAME, l as DELEGATION_STATUS_TOOL_NAME, m as DELEGATION_HISTORY_TOOL_NAME, mt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, o as createMcpServer, p as DELEGATION_HISTORY_INPUT_SCHEMA, q as createDelegationTraceCollector, s as DELEGATION_STATUS_DESCRIPTION, u as createDelegationStatusHandler, v as DELEGATE_UI_AUDIT_INPUT_SCHEMA, w as DELEGATE_FEEDBACK_TOOL_NAME, x as validateDelegateUiAuditArgs, y as DELEGATE_UI_AUDIT_TOOL_NAME } from "../supervise-
|
|
4
|
+
import { W as selectValidWinner, m as runCoderChecks, q as assertTraceDerivedFindings } from "../runtime-bCvzR6fc.js";
|
|
5
|
+
import { $ as eventToSnapshot, A as createDelegateHandler, B as DelegationTaskQueue, Bt as runAgentRounds, C as DELEGATE_FEEDBACK_INPUT_SCHEMA, D as DELEGATE_DESCRIPTION, E as validateDelegateFeedbackArgs, G as capDelegationTrace, H as DELEGATION_TRACE_MAX_BYTES, J as DelegationPersistenceError, K as composeLoopTraceEmitters, O as DELEGATE_INPUT_SCHEMA, Q as InMemoryFeedbackStore, Rt as createSandboxForSpec, S as DELEGATE_FEEDBACK_DESCRIPTION, T as createDelegateFeedbackHandler, U as DELEGATION_TRACE_MAX_SPANS, V as hashIdempotencyInput, W as buildDelegationTraceSpans, X as FileDelegationStore, Y as DelegationStateCorruptError, Z as InMemoryDelegationStore, _ as DELEGATE_UI_AUDIT_DESCRIPTION, a as createInProcessTransport, b as createDelegateUiAuditHandler, c as DELEGATION_STATUS_INPUT_SCHEMA, d as validateDelegationStatusArgs, f as DELEGATION_HISTORY_DESCRIPTION, g as validateDelegationHistoryArgs, h as createDelegationHistoryHandler, ht as createCoordinationTools, j as validateDelegateArgs, k as DELEGATE_TOOL_NAME, l as DELEGATION_STATUS_TOOL_NAME, m as DELEGATION_HISTORY_TOOL_NAME, mt as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, o as createMcpServer, p as DELEGATION_HISTORY_INPUT_SCHEMA, q as createDelegationTraceCollector, s as DELEGATION_STATUS_DESCRIPTION, u as createDelegationStatusHandler, v as DELEGATE_UI_AUDIT_INPUT_SCHEMA, w as DELEGATE_FEEDBACK_TOOL_NAME, x as validateDelegateUiAuditArgs, y as DELEGATE_UI_AUDIT_TOOL_NAME } from "../supervise-DXjtclYS.js";
|
|
6
6
|
import { t as createStdioToolServer } from "../tool-server-RcWgLIsL.js";
|
|
7
7
|
import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
|
|
8
|
-
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-
|
|
8
|
+
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-B17qCuEc.js";
|
|
9
9
|
import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
|
|
10
10
|
import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-DL6cE2Ag.js";
|
|
11
11
|
import { n as readTraceContextFromEnv, r as traceContextToEnv, t as createPropagatingTraceEmitter } from "../trace-propagation-CJJC7SVB.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as DELEGATE_FEEDBACK_INPUT_SCHEMA, S as DELEGATE_FEEDBACK_DESCRIPTION, c as DELEGATION_STATUS_INPUT_SCHEMA, f as DELEGATION_HISTORY_DESCRIPTION, l as DELEGATION_STATUS_TOOL_NAME, m as DELEGATION_HISTORY_TOOL_NAME, p as DELEGATION_HISTORY_INPUT_SCHEMA, s as DELEGATION_STATUS_DESCRIPTION, w as DELEGATE_FEEDBACK_TOOL_NAME } from "./supervise-
|
|
1
|
+
import { C as DELEGATE_FEEDBACK_INPUT_SCHEMA, S as DELEGATE_FEEDBACK_DESCRIPTION, c as DELEGATION_STATUS_INPUT_SCHEMA, f as DELEGATION_HISTORY_DESCRIPTION, l as DELEGATION_STATUS_TOOL_NAME, m as DELEGATION_HISTORY_TOOL_NAME, p as DELEGATION_HISTORY_INPUT_SCHEMA, s as DELEGATION_STATUS_DESCRIPTION, w as DELEGATE_FEEDBACK_TOOL_NAME } from "./supervise-DXjtclYS.js";
|
|
2
2
|
//#region src/mcp/openai-tools.ts
|
|
3
3
|
function buildTool(name, description, parameters) {
|
|
4
4
|
return {
|
|
@@ -41,4 +41,4 @@ function mcpToolsForRuntimeMcpSubset(names) {
|
|
|
41
41
|
//#endregion
|
|
42
42
|
export { mcpToolsForRuntimeMcpSubset as n, mcpToolsForRuntimeMcp as t };
|
|
43
43
|
|
|
44
|
-
//# sourceMappingURL=openai-tools-
|
|
44
|
+
//# sourceMappingURL=openai-tools-B17qCuEc.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-tools-
|
|
1
|
+
{"version":3,"file":"openai-tools-B17qCuEc.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when configuring `createOpenAICompatibleBackend({ tools: ... })` so the\n * model can call `delegate_feedback`, `delegation_status`, and\n * `delegation_history` through the OpenAI-compat transport (tcloud, OpenRouter,\n * OpenAI direct, cli-bridge). The runtime surfaces tool calls as `tool_call`\n * stream events — execution is the caller's responsibility (typically the\n * parent sandbox runtime's MCP mount).\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compat backend JSON-serializes the body so a shallow copy\n // into a plain object is sufficient — and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAwCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as AgentExecutionBackend, r as AgentBackendInput } from "../types-C9j4qg6l.js";
|
|
2
|
-
import { xt as createOpenAICompatibleBackend } from "../index-
|
|
2
|
+
import { xt as createOpenAICompatibleBackend } from "../index-lpqu3wdI.js";
|
|
3
3
|
import { RunRecord } from "@tangle-network/agent-eval";
|
|
4
4
|
//#region src/primeintellect/types.d.ts
|
|
5
5
|
type PrimeIntellectSplit = 'train' | 'eval';
|
|
@@ -6,7 +6,7 @@ import { i as redactProtectedValue, r as redactProtectedReason } from "./protect
|
|
|
6
6
|
import { D as routerChatWithUsage, T as routerBrain, d as settledToIteration, k as runBrainLoop, l as withDriverExecutor, t as createSupervisor, w as notifyRuntimeHookEvent } from "./supervisor-B2LzaWRb.js";
|
|
7
7
|
import { C as observe, O as strategyAuthorMethod, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-BC81Otmc.js";
|
|
8
8
|
import { a as notifySandboxEventObserver, i as mapSandboxToolEvent, r as mapSandboxEvent, t as createSandboxToolPartState } from "./sandbox-events-DeI5xX8P.js";
|
|
9
|
-
import { Bt as runAgentRounds, Dt as createExecutorRegistry, Et as createExecutor, Ht as createSandboxLineage, Ot as createWorktreeCliExecutor, Ut as probeSandboxCapabilities, bt as rollingDispatch, qt as gateOnDeliverable, t as supervise, zt as defaultSelectWinner } from "./supervise-
|
|
9
|
+
import { Bt as runAgentRounds, Dt as createExecutorRegistry, Et as createExecutor, Ht as createSandboxLineage, Ot as createWorktreeCliExecutor, Ut as probeSandboxCapabilities, bt as rollingDispatch, qt as gateOnDeliverable, t as supervise, zt as defaultSelectWinner } from "./supervise-DXjtclYS.js";
|
|
10
10
|
import { CODING_HARNESSES, InMemoryTraceStore, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, harnessAxisOf, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, scoreKnowledgeReadiness, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
11
11
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
12
12
|
import { canonicalCandidateDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
@@ -3792,14 +3792,14 @@ Rules:
|
|
|
3792
3792
|
you reached (keep-best, never final-state), progression = score after each shot.
|
|
3793
3793
|
- The module must be EXACTLY this shape (no other imports, no commentary outside code):
|
|
3794
3794
|
|
|
3795
|
-
import { defineStrategy } from '@tangle-network/agent-runtime/
|
|
3795
|
+
import { defineStrategy } from '@tangle-network/agent-runtime/kernel'
|
|
3796
3796
|
export default defineStrategy('your-strategy-name', async ({ surface, task, budget, shot, critique, listTools }) => {
|
|
3797
3797
|
// your composition (listTools comes from the destructured context — it is NOT a global)
|
|
3798
3798
|
})
|
|
3799
3799
|
`;
|
|
3800
3800
|
/** Static CONTRACT lint over an authored strategy module — the module-boundary
|
|
3801
3801
|
* enforcement of the harness's two measurement invariants:
|
|
3802
|
-
* - author blindness: the only import allowed is the
|
|
3802
|
+
* - author blindness: the only import allowed is the kernel surface. A body that could
|
|
3803
3803
|
* reach the filesystem, network, or process could read or mutate verifier/artifact
|
|
3804
3804
|
* state outside the brokered shots, and the harness-verified score would stop
|
|
3805
3805
|
* meaning "what the shots achieved".
|
|
@@ -3808,7 +3808,7 @@ export default defineStrategy('your-strategy-name', async ({ surface, task, budg
|
|
|
3808
3808
|
* equal-budget comparisons between strategies valid.
|
|
3809
3809
|
* A lint, not a sandbox: its job is keeping the benchmark numbers interpretable. */
|
|
3810
3810
|
function assertStrategyContract(code) {
|
|
3811
|
-
const allowedImport = /^\s*import\s+\{[^}]*\}\s+from\s+['"]@tangle-network\/agent-runtime\/
|
|
3811
|
+
const allowedImport = /^\s*import\s+\{[^}]*\}\s+from\s+['"]@tangle-network\/agent-runtime\/kernel['"]/;
|
|
3812
3812
|
for (const line of code.split("\n")) if (/^\s*import\s/.test(line) && !allowedImport.test(line)) throw new Error(`authored code rejected: foreign import — ${line.trim().slice(0, 120)}`);
|
|
3813
3813
|
for (const [re, what] of [
|
|
3814
3814
|
[/\brequire\s*\(/, "require()"],
|
|
@@ -5412,4 +5412,4 @@ function tail(s) {
|
|
|
5412
5412
|
//#endregion
|
|
5413
5413
|
export { defineLeaderboard as $, trajectoryReport as A, flatWidenGate as B, strategyAuthorContract as C, sanitizeMcpToolSchema as Ct, runBenchmark as D, secretEnvOfMcpServer as Dt, printBenchmarkReport as E, resolveSecretEnv as Et, registerShape as F, verify as G, panel as H, FileCorpus as I, buildSteerContext as J, widen as K, InMemoryCorpus as L, runPersonified as M, builtinShapes as N, promotionGate as O, createShapeRegistry as P, harvestCorpus as Q, renderCorpusToInstructions as R, authorStrategy as S, createMcpEnvironment as St, openSandboxRun as T, mcpSecretEnvMetadataKey as Tt, pipeline as U, loopUntil as V, selectValidWinner as W, registryScopeAnalyst as X, createScopeAnalyst as Y, inProcessSandboxClient as Z, discriminatingMeans as _, auditIntent as _t, localShell as a, loopCampaignDispatch as at, selectChampion as b, connectStdioMcp as bt, createVerifierEnvironment as c, deterministicCompletion as ct, worktreeFanout as d, leaderboard as dt, dumbDriver as et, analyzeTrace as f, pairwiseSignificance as ft, streamAgentTurn as g, renderPairwiseMarkdown as gt, collectAgentTurn as h, renderLeaderboardSvg as ht, jjWorkspace as i, inlineSandboxClient as it, definePersona as j, equalKOnCost as k, failuresAnalyst as l, sentinelCompletion as lt, runCoderChecks as m, renderLeaderboardMarkdown as mt, makeFinding$1 as n, resolveSandboxClient as nt, runInWorkspace as o, loopDispatch as ot, patchDelivered as p, renderLeaderboardHtml as pt, assertTraceDerivedFindings as q, gitWorkspace as r, localSandboxClient as rt, createWaterfallCollector as s, completionAuthorizes as st, computeFindingId$1 as t, naiveDriver as tt, superviseSurface as u, stopSentinel as ut, pickChampion as v, defaultAuditorInstruction as vt, SandboxRunAbortError as w, envKeyProvider as wt, assertStrategyContract as x, materializeLocalMcp as xt, runStrategyEvolution as y, McpSpawnFault as yt, fanout as z };
|
|
5414
5414
|
|
|
5415
|
-
//# sourceMappingURL=runtime-
|
|
5415
|
+
//# sourceMappingURL=runtime-bCvzR6fc.js.map
|