@tangle-network/agent-runtime 0.169.0 → 0.170.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/dist/{activation-CIwer0zU.js → activation-8RxHIo02.js} +2 -2
- package/dist/{activation-CIwer0zU.js.map → activation-8RxHIo02.js.map} +1 -1
- package/dist/agent.js +1 -1
- package/dist/authored-code-C2TGxNtf.js +44 -0
- package/dist/authored-code-C2TGxNtf.js.map +1 -0
- package/dist/graph.d.ts +15 -12
- package/dist/graph.js +1 -29
- package/dist/graph.js.map +1 -1
- package/dist/{improvement-cycle-BAKN_f4x.js → improvement-cycle-BYCnKZ_G.js} +24 -3
- package/dist/improvement-cycle-BYCnKZ_G.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/intelligence.js +2 -2
- package/dist/kernel.js +1 -1
- package/dist/{knowledge-D-7PXKUV.js → knowledge-D3211Z_x.js} +2 -2
- package/dist/{knowledge-D-7PXKUV.js.map → knowledge-D3211Z_x.js.map} +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-DHxQ_VQD.js → loop-runner-bin-B_g5JOKA.js} +2 -2
- package/dist/{loop-runner-bin-DHxQ_VQD.js.map → loop-runner-bin-B_g5JOKA.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/{runtime-D5l-enW9.js → runtime-C-7uhhFs.js} +3 -13
- package/dist/{runtime-D5l-enW9.js.map → runtime-C-7uhhFs.js.map} +1 -1
- package/dist/testing.js +9 -9
- package/package.json +1 -1
- package/skills/codemode/SKILL.md +48 -0
- package/dist/improvement-cycle-BAKN_f4x.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { at as canonicalCandidateDocument, ct as immutableCandidateValue, dt as verifyCanonicalCandidateDocument, it as canonicalCandidateDigest$1 } from "./prepare-BAyaNoZu.js";
|
|
2
|
-
import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-
|
|
2
|
+
import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-BYCnKZ_G.js";
|
|
3
3
|
import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentProfileImprovementExperimentSchema } from "@tangle-network/agent-interface";
|
|
4
4
|
//#region src/intelligence/activation.ts
|
|
5
5
|
/** Create the exact result a product stores in the same transaction as its target write. */
|
|
@@ -201,4 +201,4 @@ function targetIdentity(target) {
|
|
|
201
201
|
//#endregion
|
|
202
202
|
export { executeAgentImprovementActivation as n, verifyAgentImprovementActivationResult as r, createAgentImprovementActivationResult as t };
|
|
203
203
|
|
|
204
|
-
//# sourceMappingURL=activation-
|
|
204
|
+
//# sourceMappingURL=activation-8RxHIo02.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activation-CIwer0zU.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/activation.ts"],"sourcesContent":["import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;;AA6I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AAkB,QAAQ,IAAI,eAAe,MAAM,CAAC,CACzE;CACA,IAAI,OAAO,QAAQ,WAAW,mBAAmB;EAC/C,IAAI,CAAC,YAAY,MAAM,IAAI,MAAM,0DAA0D;EAC3F;CACF;CACA,MAAM,aAAa,UAAU,WAAW,OAAO;CAC/C,MAAM,iBAAiB,OAAO,QAAQ,QAAQ,MAC3C,WAAW,OAAO,kBAAkB,WAAW,IAAI,eAAe,MAAM,CAAC,CAAC,EAAE,kBAC/E;CACA,IAAI,cAAc,CAAC,gBACjB,MAAM,IAAI,MAAM,0DAA0D;AAE9E;AAEA,SAAS,UACP,SACgB;CAChB,OAAO,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
|
|
1
|
+
{"version":3,"file":"activation-8RxHIo02.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/activation.ts"],"sourcesContent":["import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;;AA6IA,SAAgB,uCACd,YACA,SACkC;CAClC,MAAM,aAAa,iCACjB,iCAAiC,MAAM,WAAW,UAAU,GAC5D,8BACF;CACA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CAAC,YAAY,MAAM,IAAI,MAAM,0DAA0D;EAC3F;CACF;CACA,MAAM,aAAa,UAAU,WAAW,OAAO;CAC/C,MAAM,iBAAiB,OAAO,QAAQ,QAAQ,MAC3C,WAAW,OAAO,kBAAkB,WAAW,IAAI,eAAe,MAAM,CAAC,CAAC,EAAE,kBAC/E;CACA,IAAI,cAAc,CAAC,gBACjB,MAAM,IAAI,MAAM,0DAA0D;AAE9E;AAEA,SAAS,UACP,SACgB;CAChB,OAAO,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
|
package/dist/agent.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { o as mapSandboxEvent } from "./sandbox-events-BVjstFgb.js";
|
|
2
2
|
import { Sn as worktreeCliProfileMaterialization, _n as renderProfileMaterializationIssues, _t as createSandboxForSpec, cn as assertProfileMaterialization, dn as fullProfileMaterialization, fn as profileMaterializationAxes, gn as promptResourceProfileMaterialization, hn as promptOnlyProfileMaterialization, ln as controlProfileMaterialization, mn as promptModelProfileMaterialization, pn as promptControlProfileMaterialization, sn as AGENT_PROFILE_MATERIALIZATION_AXES, un as defineProfileMaterializationContract, xn as validateProfileMaterialization, yn as sandboxActProfileMaterialization } from "./supervisor-B-mmmiOU.js";
|
|
3
|
-
import "./runtime-
|
|
3
|
+
import "./runtime-C-7uhhFs.js";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
6
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { m as ValidationError } from "./errors-CDZ8XsVj.js";
|
|
2
|
+
//#region src/runtime/authored-code.ts
|
|
3
|
+
/**
|
|
4
|
+
* The ONE lint over model-authored source, and the fence extractor beside it.
|
|
5
|
+
*
|
|
6
|
+
* Two features have a model write code the runtime then runs: `authorStrategy` (an authored
|
|
7
|
+
* optimization strategy, since 0.60) and the graph engine's `codemode` node (0.169.0). Both need
|
|
8
|
+
* the same refusals; 0.169.0 shipped them as two byte-near copies that could drift independently,
|
|
9
|
+
* which an audit flagged. This module is the single copy both import.
|
|
10
|
+
*
|
|
11
|
+
* A LINT, NOT A SANDBOX — it reads text and cannot constrain what running code does. Its job is
|
|
12
|
+
* refusing the obvious escapes in the authored source so a bad program is rejected before
|
|
13
|
+
* anything executes. Isolation, where required, is the execution boundary's job (a jailed
|
|
14
|
+
* `codeRunner`, a sandboxed loader), never this check's.
|
|
15
|
+
*/
|
|
16
|
+
/** Refuse the obvious escapes in authored source. See the module doc for what this is NOT. */
|
|
17
|
+
function assertAuthoredCode(code, options = {}) {
|
|
18
|
+
const context = options.context ?? "authored code";
|
|
19
|
+
const allowed = options.allowedImports ?? [];
|
|
20
|
+
for (const line of code.split("\n")) {
|
|
21
|
+
if (!/^\s*import\s/.test(line)) continue;
|
|
22
|
+
if (!allowed.some((specifier) => line.includes(`'${specifier}'`) || line.includes(`"${specifier}"`))) throw new ValidationError(`${context} rejected: foreign import — ${line.trim().slice(0, 120)}${allowed.length === 0 ? " (no import is allowed here)" : ` (allowed: ${allowed.join(", ")})`}`);
|
|
23
|
+
}
|
|
24
|
+
for (const [pattern, what] of [
|
|
25
|
+
[/\brequire\s*\(/, "require()"],
|
|
26
|
+
[/\bimport\s*\(/, "dynamic import()"],
|
|
27
|
+
[/\beval\s*\(/, "eval()"],
|
|
28
|
+
[/new\s+Function\s*\(/, "new Function()"],
|
|
29
|
+
[/\bprocess\s*[.[]/, "process access"],
|
|
30
|
+
[/\bglobalThis\s*[.[]/, "globalThis access"],
|
|
31
|
+
[/\bfetch\s*\(/, "network access"],
|
|
32
|
+
[/child_process|node:fs|node:net|node:http|worker_threads/, "node builtin access"]
|
|
33
|
+
]) if (pattern.test(code)) throw new ValidationError(`${context} rejected: ${what}`);
|
|
34
|
+
}
|
|
35
|
+
/** Pull the first fenced block out of a model reply; the whole reply if it carries no fence. */
|
|
36
|
+
function extractCodeBlock(reply) {
|
|
37
|
+
const code = (/```(?:[a-zA-Z]*)\n([\s\S]*?)```/u.exec(reply)?.[1] ?? reply).trim();
|
|
38
|
+
if (code.length === 0) throw new ValidationError("authored code: the model returned no code");
|
|
39
|
+
return code;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { extractCodeBlock as n, assertAuthoredCode as t };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=authored-code-C2TGxNtf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authored-code-C2TGxNtf.js","names":[],"sources":["../src/runtime/authored-code.ts"],"sourcesContent":["/**\n * The ONE lint over model-authored source, and the fence extractor beside it.\n *\n * Two features have a model write code the runtime then runs: `authorStrategy` (an authored\n * optimization strategy, since 0.60) and the graph engine's `codemode` node (0.169.0). Both need\n * the same refusals; 0.169.0 shipped them as two byte-near copies that could drift independently,\n * which an audit flagged. This module is the single copy both import.\n *\n * A LINT, NOT A SANDBOX — it reads text and cannot constrain what running code does. Its job is\n * refusing the obvious escapes in the authored source so a bad program is rejected before\n * anything executes. Isolation, where required, is the execution boundary's job (a jailed\n * `codeRunner`, a sandboxed loader), never this check's.\n */\nimport { ValidationError } from '../errors'\n\nexport interface AuthoredCodeOptions {\n /** Import specifiers an authored module may name. Empty (the default) bans every import. A\n * specifier admits ANY import form of that module (named, namespace, default) — the lint\n * gates WHICH module, not the syntax used to reach it. */\n readonly allowedImports?: ReadonlyArray<string>\n /** Names the refusal, e.g. `codemode \"planner\"`. Defaults to `authored code`. */\n readonly context?: string\n}\n\n/** Refuse the obvious escapes in authored source. See the module doc for what this is NOT. */\nexport function assertAuthoredCode(code: string, options: AuthoredCodeOptions = {}): void {\n const context = options.context ?? 'authored code'\n const allowed = options.allowedImports ?? []\n for (const line of code.split('\\n')) {\n if (!/^\\s*import\\s/.test(line)) continue\n const named = allowed.some(\n (specifier) => line.includes(`'${specifier}'`) || line.includes(`\"${specifier}\"`),\n )\n if (!named) {\n throw new ValidationError(\n `${context} rejected: foreign import — ${line.trim().slice(0, 120)}${\n allowed.length === 0\n ? ' (no import is allowed here)'\n : ` (allowed: ${allowed.join(', ')})`\n }`,\n )\n }\n }\n const banned: ReadonlyArray<readonly [RegExp, string]> = [\n [/\\brequire\\s*\\(/, 'require()'],\n [/\\bimport\\s*\\(/, 'dynamic import()'],\n [/\\beval\\s*\\(/, 'eval()'],\n [/new\\s+Function\\s*\\(/, 'new Function()'],\n [/\\bprocess\\s*[.[]/, 'process access'],\n [/\\bglobalThis\\s*[.[]/, 'globalThis access'],\n [/\\bfetch\\s*\\(/, 'network access'],\n [/child_process|node:fs|node:net|node:http|worker_threads/, 'node builtin access'],\n ]\n for (const [pattern, what] of banned) {\n if (pattern.test(code)) throw new ValidationError(`${context} rejected: ${what}`)\n }\n}\n\n/** Pull the first fenced block out of a model reply; the whole reply if it carries no fence. */\nexport function extractCodeBlock(reply: string): string {\n const fenced = /```(?:[a-zA-Z]*)\\n([\\s\\S]*?)```/u.exec(reply)\n const code = (fenced?.[1] ?? reply).trim()\n if (code.length === 0) throw new ValidationError('authored code: the model returned no code')\n return code\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,SAAgB,mBAAmB,MAAc,UAA+B,CAAC,GAAS;CACxF,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,UAAU,QAAQ,kBAAkB,CAAC;CAC3C,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG;EAIhC,IAAI,CAHU,QAAQ,MACnB,cAAc,KAAK,SAAS,IAAI,UAAU,EAAE,KAAK,KAAK,SAAS,IAAI,UAAU,EAAE,CAEzE,GACP,MAAM,IAAI,gBACR,GAAG,QAAQ,8BAA8B,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,GAAG,IAC/D,QAAQ,WAAW,IACf,iCACA,cAAc,QAAQ,KAAK,IAAI,EAAE,IAEzC;CAEJ;CAWA,KAAK,MAAM,CAAC,SAAS,SAAS;EAT5B,CAAC,kBAAkB,WAAW;EAC9B,CAAC,iBAAiB,kBAAkB;EACpC,CAAC,eAAe,QAAQ;EACxB,CAAC,uBAAuB,gBAAgB;EACxC,CAAC,oBAAoB,gBAAgB;EACrC,CAAC,uBAAuB,mBAAmB;EAC3C,CAAC,gBAAgB,gBAAgB;EACjC,CAAC,2DAA2D,qBAAqB;CAEhD,GACjC,IAAI,QAAQ,KAAK,IAAI,GAAG,MAAM,IAAI,gBAAgB,GAAG,QAAQ,aAAa,MAAM;AAEpF;;AAGA,SAAgB,iBAAiB,OAAuB;CAEtD,MAAM,QADS,mCAAmC,KAAK,KACpC,CAAC,GAAG,MAAM,MAAA,CAAO,KAAK;CACzC,IAAI,KAAK,WAAW,GAAG,MAAM,IAAI,gBAAgB,2CAA2C;CAC5F,OAAO;AACT"}
|
package/dist/graph.d.ts
CHANGED
|
@@ -2,6 +2,20 @@ import { $l as MakeWorkerAgent, Gt as AgentGraph, If as DeliverableSpec, Qt as R
|
|
|
2
2
|
import { H as SpawnJournal, K as Spend, V as SpawnEvent, i as Budget, j as ResultBlobStore, t as Agent, z as Scope } from "./types-DjVO-p7R.js";
|
|
3
3
|
import { o as ExecutorConfig } from "./runtime-B0HZbuEv.js";
|
|
4
4
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
5
|
+
//#region src/runtime/authored-code.d.ts
|
|
6
|
+
interface AuthoredCodeOptions {
|
|
7
|
+
/** Import specifiers an authored module may name. Empty (the default) bans every import. A
|
|
8
|
+
* specifier admits ANY import form of that module (named, namespace, default) — the lint
|
|
9
|
+
* gates WHICH module, not the syntax used to reach it. */
|
|
10
|
+
readonly allowedImports?: ReadonlyArray<string>;
|
|
11
|
+
/** Names the refusal, e.g. `codemode "planner"`. Defaults to `authored code`. */
|
|
12
|
+
readonly context?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Refuse the obvious escapes in authored source. See the module doc for what this is NOT. */
|
|
15
|
+
declare function assertAuthoredCode(code: string, options?: AuthoredCodeOptions): void;
|
|
16
|
+
/** Pull the first fenced block out of a model reply; the whole reply if it carries no fence. */
|
|
17
|
+
declare function extractCodeBlock(reply: string): string;
|
|
18
|
+
//#endregion
|
|
5
19
|
//#region src/runtime/graph/registry.d.ts
|
|
6
20
|
/**
|
|
7
21
|
* `Registry<T>` — the ONE name→thing shape for the graph engine.
|
|
@@ -218,19 +232,8 @@ interface CodeModeConfig {
|
|
|
218
232
|
/** Import specifiers the authored code may name. Empty (the default) bans every import. */
|
|
219
233
|
readonly allowedImports?: ReadonlyArray<string>;
|
|
220
234
|
}
|
|
221
|
-
/**
|
|
222
|
-
* Refuse the obvious escapes in authored source. A LINT, not a sandbox: it reads text and cannot
|
|
223
|
-
* constrain what running code does. Generalized from `strategy-author.ts`'s contract check, which
|
|
224
|
-
* has guarded agent-authored optimization strategies since 0.60.
|
|
225
|
-
*/
|
|
226
|
-
declare function assertAuthoredCode(code: string, options?: {
|
|
227
|
-
readonly allowedImports?: ReadonlyArray<string>;
|
|
228
|
-
readonly context?: string;
|
|
229
|
-
}): void;
|
|
230
235
|
/** The API doc the model is shown — generated from the grant, so the two cannot disagree. */
|
|
231
236
|
declare function renderCodeApi(config: CodeModeConfig): string;
|
|
232
|
-
/** Pull the first fenced block out of a model reply; the whole reply if it carries no fence. */
|
|
233
|
-
declare function extractCodeBlock(reply: string): string;
|
|
234
237
|
/**
|
|
235
238
|
* A node that asks a model for a program and runs it. Declares the two effects it cannot supply
|
|
236
239
|
* itself — `model` (who writes the code) and `codeRunner` (where it runs) — so the host owns both.
|
|
@@ -798,5 +801,5 @@ declare function runEngineGraph(engine: GraphEngine, spec: EngineGraphSpec | Com
|
|
|
798
801
|
*/
|
|
799
802
|
declare function createGraphRun(engine: GraphEngine, spec: EngineGraphSpec | CompiledGraph, task: string, options: GraphRunOptions): GraphRunHandle;
|
|
800
803
|
//#endregion
|
|
801
|
-
export { type AgentKindConfig, type AnyNodeKind, type BudgetMode, CONDITION_OPS, type CodeAuthor, type CodeModeConfig, type CodeOperation, type CodeOperationResult, type CodeRunner, type CompiledEdge, type CompiledGraph, type CompiledNode, type Condition, type ConditionLeaf, type ConditionOp, DEFAULT_MAX_NODE_VISITS, ENGINE_WOKEN_SEQ_BASE, type EdgeLedger, type EffectContext, type EffectName, type EngineGraphEdge, type EngineGraphNode, type EngineGraphSpec, type FinalizerChoice, type FoldEdge, type FoldEdgeState, type FoldInstance, type FoldInstanceStatus, type FoldNode, type FoldSuspension, type GatingEdge, type GraphEdgeKind, type GraphEdgeTraversal, type GraphEngine, type GraphEngineOptions, type GraphFoldState, type GraphHost, type GraphNodeSettle, type GraphRunContext, type GraphRunHandle, type GraphRunOptions, type GraphRunReason, type GraphRunResult, JOIN_RULES, type JoinDecision, type JoinRule, type JsonSchema, MAX_MAX_NODE_VISITS, type NodeFlags, type NodeKind, type OnCrash, type PortSpec, type Projection, RUN_GRAPH_ROOT_KIND, type Registered, type Registry, type RegistryHandle, type ScriptBody, type ScriptKindConfig, type SubgraphKindConfig, type SupervisorKindConfig, type SuspensionRequest, admitPayload, agentKind, applyGraphFoldEvent, applyProjection, assembleGraphResult, assertAuthoredCode, codemodeKind, compileGraph, createEdgeLedger, createGraphEngine, createGraphRun, createRegistry, decideJoin, emptyFoldState, evaluateCondition, extractCodeBlock, foldGraphJournal, formatRegistryHandle, graphFromRunGraph, inlineCodeRunner, isEngineFired, isSuspensionRequest, kindHandle, materializeSettles, mintSuspensionToken, narrowEffects, openGraphRun, parseRegistryHandle, renderCodeApi, runEngineGraph, schemaAccepts, scriptKind, subgraphKind, supervisorKind, suspended, suspensionNodeId, tokenFromSuspensionNodeId, validateCondition, validateNodeKind, validateProjection };
|
|
804
|
+
export { type AgentKindConfig, type AnyNodeKind, type AuthoredCodeOptions, type BudgetMode, CONDITION_OPS, type CodeAuthor, type CodeModeConfig, type CodeOperation, type CodeOperationResult, type CodeRunner, type CompiledEdge, type CompiledGraph, type CompiledNode, type Condition, type ConditionLeaf, type ConditionOp, DEFAULT_MAX_NODE_VISITS, ENGINE_WOKEN_SEQ_BASE, type EdgeLedger, type EffectContext, type EffectName, type EngineGraphEdge, type EngineGraphNode, type EngineGraphSpec, type FinalizerChoice, type FoldEdge, type FoldEdgeState, type FoldInstance, type FoldInstanceStatus, type FoldNode, type FoldSuspension, type GatingEdge, type GraphEdgeKind, type GraphEdgeTraversal, type GraphEngine, type GraphEngineOptions, type GraphFoldState, type GraphHost, type GraphNodeSettle, type GraphRunContext, type GraphRunHandle, type GraphRunOptions, type GraphRunReason, type GraphRunResult, JOIN_RULES, type JoinDecision, type JoinRule, type JsonSchema, MAX_MAX_NODE_VISITS, type NodeFlags, type NodeKind, type OnCrash, type PortSpec, type Projection, RUN_GRAPH_ROOT_KIND, type Registered, type Registry, type RegistryHandle, type ScriptBody, type ScriptKindConfig, type SubgraphKindConfig, type SupervisorKindConfig, type SuspensionRequest, admitPayload, agentKind, applyGraphFoldEvent, applyProjection, assembleGraphResult, assertAuthoredCode, codemodeKind, compileGraph, createEdgeLedger, createGraphEngine, createGraphRun, createRegistry, decideJoin, emptyFoldState, evaluateCondition, extractCodeBlock, foldGraphJournal, formatRegistryHandle, graphFromRunGraph, inlineCodeRunner, isEngineFired, isSuspensionRequest, kindHandle, materializeSettles, mintSuspensionToken, narrowEffects, openGraphRun, parseRegistryHandle, renderCodeApi, runEngineGraph, schemaAccepts, scriptKind, subgraphKind, supervisorKind, suspended, suspensionNodeId, tokenFromSuspensionNodeId, validateCondition, validateNodeKind, validateProjection };
|
|
802
805
|
//# sourceMappingURL=graph.d.ts.map
|
package/dist/graph.js
CHANGED
|
@@ -3,32 +3,10 @@ import { d as replaySpawnTree, i as InMemorySpawnJournal, l as materializeTreeVi
|
|
|
3
3
|
import { t as addSpend } from "./util-D6ZEuBMi.js";
|
|
4
4
|
import { N as createBudgetPool, U as createExecutorRegistry, a as uncertainSpawnBudgets, i as sumMeasuredSpendFromEvents, l as runFinalizer, o as bestDelivered, p as createScope, r as maxSeqOf, s as collectDelivered } from "./supervisor-B-mmmiOU.js";
|
|
5
5
|
import { i as workerFromBackend, s as supervisorAgent } from "./supervise-rEE46ruH.js";
|
|
6
|
+
import { n as extractCodeBlock, t as assertAuthoredCode } from "./authored-code-C2TGxNtf.js";
|
|
6
7
|
import { t as GraphEdgeCapError } from "./graph-ZDMygFIo.js";
|
|
7
8
|
//#region src/runtime/graph/codemode.ts
|
|
8
9
|
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
|
|
9
|
-
/**
|
|
10
|
-
* Refuse the obvious escapes in authored source. A LINT, not a sandbox: it reads text and cannot
|
|
11
|
-
* constrain what running code does. Generalized from `strategy-author.ts`'s contract check, which
|
|
12
|
-
* has guarded agent-authored optimization strategies since 0.60.
|
|
13
|
-
*/
|
|
14
|
-
function assertAuthoredCode(code, options = {}) {
|
|
15
|
-
const context = options.context ?? "authored code";
|
|
16
|
-
const allowed = options.allowedImports ?? [];
|
|
17
|
-
for (const line of code.split("\n")) {
|
|
18
|
-
if (!/^\s*import\s/.test(line)) continue;
|
|
19
|
-
if (!allowed.some((specifier) => line.includes(`'${specifier}'`) || line.includes(`"${specifier}"`))) throw new ValidationError(`${context} rejected: foreign import — ${line.trim().slice(0, 120)}${allowed.length === 0 ? " (no import is allowed here)" : ` (allowed: ${allowed.join(", ")})`}`);
|
|
20
|
-
}
|
|
21
|
-
for (const [pattern, what] of [
|
|
22
|
-
[/\brequire\s*\(/, "require()"],
|
|
23
|
-
[/\bimport\s*\(/, "dynamic import()"],
|
|
24
|
-
[/\beval\s*\(/, "eval()"],
|
|
25
|
-
[/new\s+Function\s*\(/, "new Function()"],
|
|
26
|
-
[/\bprocess\s*[.[]/, "process access"],
|
|
27
|
-
[/\bglobalThis\s*[.[]/, "globalThis access"],
|
|
28
|
-
[/\bfetch\s*\(/, "network access"],
|
|
29
|
-
[/child_process|node:fs|node:net|node:http|worker_threads/, "node builtin access"]
|
|
30
|
-
]) if (pattern.test(code)) throw new ValidationError(`${context} rejected: ${what}`);
|
|
31
|
-
}
|
|
32
10
|
/** The API doc the model is shown — generated from the grant, so the two cannot disagree. */
|
|
33
11
|
function renderCodeApi(config) {
|
|
34
12
|
return [
|
|
@@ -42,12 +20,6 @@ function renderCodeApi(config) {
|
|
|
42
20
|
`TASK: ${config.task}`
|
|
43
21
|
].join("\n");
|
|
44
22
|
}
|
|
45
|
-
/** Pull the first fenced block out of a model reply; the whole reply if it carries no fence. */
|
|
46
|
-
function extractCodeBlock(reply) {
|
|
47
|
-
const code = (/```(?:[a-zA-Z]*)\n([\s\S]*?)```/u.exec(reply)?.[1] ?? reply).trim();
|
|
48
|
-
if (code.length === 0) throw new ValidationError("codemode: the model returned no code");
|
|
49
|
-
return code;
|
|
50
|
-
}
|
|
51
23
|
/**
|
|
52
24
|
* A node that asks a model for a program and runs it. Declares the two effects it cannot supply
|
|
53
25
|
* itself — `model` (who writes the code) and `codeRunner` (where it runs) — so the host owns both.
|