agentfootprint 2.11.0 → 2.11.2

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.
Files changed (110) hide show
  1. package/README.md +2 -1
  2. package/dist/core/Agent.js +89 -1341
  3. package/dist/core/Agent.js.map +1 -1
  4. package/dist/core/agent/AgentBuilder.js +489 -0
  5. package/dist/core/agent/AgentBuilder.js.map +1 -0
  6. package/dist/core/agent/buildAgentChart.js +227 -0
  7. package/dist/core/agent/buildAgentChart.js.map +1 -0
  8. package/dist/core/agent/buildToolRegistry.js +115 -0
  9. package/dist/core/agent/buildToolRegistry.js.map +1 -0
  10. package/dist/core/agent/stages/breakFinal.js +28 -0
  11. package/dist/core/agent/stages/breakFinal.js.map +1 -0
  12. package/dist/core/agent/stages/callLLM.js +129 -0
  13. package/dist/core/agent/stages/callLLM.js.map +1 -0
  14. package/dist/core/agent/stages/iterationStart.js +24 -0
  15. package/dist/core/agent/stages/iterationStart.js.map +1 -0
  16. package/dist/core/agent/stages/prepareFinal.js +45 -0
  17. package/dist/core/agent/stages/prepareFinal.js.map +1 -0
  18. package/dist/core/agent/stages/route.js +36 -0
  19. package/dist/core/agent/stages/route.js.map +1 -0
  20. package/dist/core/agent/stages/seed.js +95 -0
  21. package/dist/core/agent/stages/seed.js.map +1 -0
  22. package/dist/core/agent/stages/toolCalls.js +250 -0
  23. package/dist/core/agent/stages/toolCalls.js.map +1 -0
  24. package/dist/core/agent/types.js +12 -0
  25. package/dist/core/agent/types.js.map +1 -0
  26. package/dist/core/agent/validators.js +131 -0
  27. package/dist/core/agent/validators.js.map +1 -0
  28. package/dist/esm/core/Agent.js +87 -1338
  29. package/dist/esm/core/Agent.js.map +1 -1
  30. package/dist/esm/core/agent/AgentBuilder.js +485 -0
  31. package/dist/esm/core/agent/AgentBuilder.js.map +1 -0
  32. package/dist/esm/core/agent/buildAgentChart.js +223 -0
  33. package/dist/esm/core/agent/buildAgentChart.js.map +1 -0
  34. package/dist/esm/core/agent/buildToolRegistry.js +111 -0
  35. package/dist/esm/core/agent/buildToolRegistry.js.map +1 -0
  36. package/dist/esm/core/agent/stages/breakFinal.js +24 -0
  37. package/dist/esm/core/agent/stages/breakFinal.js.map +1 -0
  38. package/dist/esm/core/agent/stages/callLLM.js +125 -0
  39. package/dist/esm/core/agent/stages/callLLM.js.map +1 -0
  40. package/dist/esm/core/agent/stages/iterationStart.js +20 -0
  41. package/dist/esm/core/agent/stages/iterationStart.js.map +1 -0
  42. package/dist/esm/core/agent/stages/prepareFinal.js +41 -0
  43. package/dist/esm/core/agent/stages/prepareFinal.js.map +1 -0
  44. package/dist/esm/core/agent/stages/route.js +32 -0
  45. package/dist/esm/core/agent/stages/route.js.map +1 -0
  46. package/dist/esm/core/agent/stages/seed.js +91 -0
  47. package/dist/esm/core/agent/stages/seed.js.map +1 -0
  48. package/dist/esm/core/agent/stages/toolCalls.js +246 -0
  49. package/dist/esm/core/agent/stages/toolCalls.js.map +1 -0
  50. package/dist/esm/core/agent/types.js +11 -0
  51. package/dist/esm/core/agent/types.js.map +1 -0
  52. package/dist/esm/core/agent/validators.js +124 -0
  53. package/dist/esm/core/agent/validators.js.map +1 -0
  54. package/dist/esm/reliability/CircuitBreaker.js +156 -0
  55. package/dist/esm/reliability/CircuitBreaker.js.map +1 -0
  56. package/dist/esm/reliability/buildReliabilityGateChart.js +359 -0
  57. package/dist/esm/reliability/buildReliabilityGateChart.js.map +1 -0
  58. package/dist/esm/reliability/classifyError.js +56 -0
  59. package/dist/esm/reliability/classifyError.js.map +1 -0
  60. package/dist/esm/reliability/index.js +36 -0
  61. package/dist/esm/reliability/index.js.map +1 -0
  62. package/dist/esm/reliability/types.js +44 -0
  63. package/dist/esm/reliability/types.js.map +1 -0
  64. package/dist/reliability/CircuitBreaker.js +165 -0
  65. package/dist/reliability/CircuitBreaker.js.map +1 -0
  66. package/dist/reliability/buildReliabilityGateChart.js +363 -0
  67. package/dist/reliability/buildReliabilityGateChart.js.map +1 -0
  68. package/dist/reliability/classifyError.js +60 -0
  69. package/dist/reliability/classifyError.js.map +1 -0
  70. package/dist/reliability/index.js +42 -0
  71. package/dist/reliability/index.js.map +1 -0
  72. package/dist/reliability/types.js +48 -0
  73. package/dist/reliability/types.js.map +1 -0
  74. package/dist/types/core/Agent.d.ts +7 -400
  75. package/dist/types/core/Agent.d.ts.map +1 -1
  76. package/dist/types/core/agent/AgentBuilder.d.ts +348 -0
  77. package/dist/types/core/agent/AgentBuilder.d.ts.map +1 -0
  78. package/dist/types/core/agent/buildAgentChart.d.ts +74 -0
  79. package/dist/types/core/agent/buildAgentChart.d.ts.map +1 -0
  80. package/dist/types/core/agent/buildToolRegistry.d.ts +62 -0
  81. package/dist/types/core/agent/buildToolRegistry.d.ts.map +1 -0
  82. package/dist/types/core/agent/stages/breakFinal.d.ts +23 -0
  83. package/dist/types/core/agent/stages/breakFinal.d.ts.map +1 -0
  84. package/dist/types/core/agent/stages/callLLM.d.ts +54 -0
  85. package/dist/types/core/agent/stages/callLLM.d.ts.map +1 -0
  86. package/dist/types/core/agent/stages/iterationStart.d.ts +16 -0
  87. package/dist/types/core/agent/stages/iterationStart.d.ts.map +1 -0
  88. package/dist/types/core/agent/stages/prepareFinal.d.ts +20 -0
  89. package/dist/types/core/agent/stages/prepareFinal.d.ts.map +1 -0
  90. package/dist/types/core/agent/stages/route.d.ts +19 -0
  91. package/dist/types/core/agent/stages/route.d.ts.map +1 -0
  92. package/dist/types/core/agent/stages/seed.d.ts +54 -0
  93. package/dist/types/core/agent/stages/seed.d.ts.map +1 -0
  94. package/dist/types/core/agent/stages/toolCalls.d.ts +50 -0
  95. package/dist/types/core/agent/stages/toolCalls.d.ts.map +1 -0
  96. package/dist/types/core/agent/types.d.ts +154 -0
  97. package/dist/types/core/agent/types.d.ts.map +1 -0
  98. package/dist/types/core/agent/validators.d.ts +48 -0
  99. package/dist/types/core/agent/validators.d.ts.map +1 -0
  100. package/dist/types/reliability/CircuitBreaker.d.ts +76 -0
  101. package/dist/types/reliability/CircuitBreaker.d.ts.map +1 -0
  102. package/dist/types/reliability/buildReliabilityGateChart.d.ts +54 -0
  103. package/dist/types/reliability/buildReliabilityGateChart.d.ts.map +1 -0
  104. package/dist/types/reliability/classifyError.d.ts +29 -0
  105. package/dist/types/reliability/classifyError.d.ts.map +1 -0
  106. package/dist/types/reliability/index.d.ts +34 -0
  107. package/dist/types/reliability/index.d.ts.map +1 -0
  108. package/dist/types/reliability/types.d.ts +256 -0
  109. package/dist/types/reliability/types.d.ts.map +1 -0
  110. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../src/core/agent/stages/route.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AAGH,uEAAiE;AAK1D,MAAM,iBAAiB,GAAG,CAAC,KAA6B,EAAe,EAAE;IAC9E,MAAM,SAAS,GAAG,KAAK,CAAC,kBAAiD,CAAC;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,SAAmB,CAAC;IAC5C,MAAM,MAAM,GACV,SAAS,CAAC,MAAM,GAAG,CAAC,IAAI,SAAS,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC;IAEnF,IAAA,wBAAS,EAAC,KAAK,EAAE,oCAAoC,EAAE;QACrD,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,SAAS;QACpB,MAAM;QACN,SAAS,EACP,MAAM,KAAK,YAAY;YACrB,CAAC,CAAC,iBAAiB,SAAS,CAAC,MAAM,eAAe;YAClD,CAAC,CAAC,SAAS,IAAI,KAAK,CAAC,aAAa;gBAClC,CAAC,CAAC,uCAAuC;gBACzC,CAAC,CAAC,2CAA2C;KAClD,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAnBW,QAAA,iBAAiB,qBAmB5B"}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /**
3
+ * seed — initial stage of the agent's chart. Initializes every mutable
4
+ * field of `AgentState` from the consumer's input.
5
+ *
6
+ * Runs once per `agent.run({ input })`. The chart is built once at
7
+ * Agent construction, so seed has access to BOTH:
8
+ *
9
+ * • CHART-BUILD-TIME constants (maxIterations, cachingDisabled,
10
+ * toolSchemas) — passed as direct values to the factory.
11
+ * • PER-RUN MUTABLE state (pendingResumeHistory from
12
+ * resumeOnError(), currentRunContext.runId set per run) —
13
+ * passed as accessor closures over the Agent instance, since
14
+ * these change between consecutive `agent.run()` invocations.
15
+ *
16
+ * The accessor pattern keeps `seed` decoupled from the Agent class
17
+ * while preserving the per-run mutability the resume + identity
18
+ * features need.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.buildSeedStage = void 0;
22
+ const typedEmit_js_1 = require("../../../recorders/core/typedEmit.js");
23
+ /**
24
+ * Build the seed stage function for an Agent instance. Captures both
25
+ * the chart-build-time constants and the per-run mutable accessors
26
+ * via the deps object.
27
+ */
28
+ function buildSeedStage(deps) {
29
+ return (scope) => {
30
+ const args = scope.$getArgs();
31
+ scope.userMessage = args.message;
32
+ // If `resumeOnError(...)` set the side channel, restore the
33
+ // checkpointed conversation history. The next iteration sees
34
+ // the prior messages and continues from the failure point.
35
+ // Always clear the field after reading so subsequent runs
36
+ // (without resumeOnError) start fresh.
37
+ const resumeHistory = deps.consumePendingResumeHistory();
38
+ if (resumeHistory && resumeHistory.length > 0) {
39
+ scope.history = [...resumeHistory];
40
+ }
41
+ else {
42
+ scope.history = [{ role: 'user', content: args.message }];
43
+ }
44
+ // Default identity uses the runId so multi-run isolation works
45
+ // without consumer changes; explicit identity (multi-tenant)
46
+ // overrides via `agent.run({ identity })`.
47
+ scope.runIdentity = args.identity ?? {
48
+ conversationId: deps.getCurrentRunId() ?? 'default',
49
+ };
50
+ scope.newMessages = [];
51
+ scope.turnNumber = 1;
52
+ // Permissive default — explicit cap will land when PricingTable
53
+ // gets a context-window field. Memory pickByBudget treats anything
54
+ // ≥ minimumTokens as "fits", so this just enables the budget path.
55
+ scope.contextTokensRemaining = 32_000;
56
+ scope.iteration = 1;
57
+ scope.maxIterations = deps.maxIterations;
58
+ scope.finalContent = '';
59
+ scope.totalInputTokens = 0;
60
+ scope.totalOutputTokens = 0;
61
+ scope.turnStartMs = Date.now();
62
+ scope.systemPromptInjections = [];
63
+ scope.messagesInjections = [];
64
+ scope.toolsInjections = [];
65
+ scope.llmLatestContent = '';
66
+ scope.llmLatestToolCalls = [];
67
+ scope.pausedToolCallId = '';
68
+ scope.pausedToolName = '';
69
+ scope.pausedToolStartMs = 0;
70
+ scope.cumTokensInput = 0;
71
+ scope.cumTokensOutput = 0;
72
+ scope.cumEstimatedUsd = 0;
73
+ scope.costBudgetHit = false;
74
+ scope.activeInjections = [];
75
+ scope.activatedInjectionIds = [];
76
+ scope.dynamicToolSchemas = deps.toolSchemas;
77
+ // Cache layer state (v2.6) — initialized to inert defaults.
78
+ // CacheDecision subflow populates `cacheMarkers` per iteration;
79
+ // UpdateSkillHistory + CacheGate consume `cachingDisabled`,
80
+ // `recentHitRate`, `skillHistory`. Empty defaults mean the
81
+ // CacheGate falls through to 'apply-markers' on iter 1 (no
82
+ // history yet → no churn detected; recentHitRate undefined →
83
+ // hit-rate floor doesn't fire).
84
+ scope.cacheMarkers = [];
85
+ scope.cachingDisabled = deps.cachingDisabled;
86
+ scope.recentHitRate = undefined;
87
+ scope.skillHistory = [];
88
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.agent.turn_start', {
89
+ turnIndex: 0,
90
+ userPrompt: args.message,
91
+ });
92
+ };
93
+ }
94
+ exports.buildSeedStage = buildSeedStage;
95
+ //# sourceMappingURL=seed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seed.js","sourceRoot":"","sources":["../../../../src/core/agent/stages/seed.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;GAiBG;;;AAIH,uEAAiE;AA8BjE;;;;GAIG;AACH,SAAgB,cAAc,CAAC,IAA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AC;QAClC,KAAK,CAAC,kBAAkB,GAAG,EAAE,CAAC;QAC9B,KAAK,CAAC,eAAe,GAAG,EAAE,CAAC;QAC3B,KAAK,CAAC,gBAAgB,GAAG,EAAE,CAAC;QAC5B,KAAK,CAAC,kBAAkB,GAAG,EAAE,CAAC;QAC9B,KAAK,CAAC,gBAAgB,GAAG,EAAE,CAAC;QAC5B,KAAK,CAAC,cAAc,GAAG,EAAE,CAAC;QAC1B,KAAK,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC5B,KAAK,CAAC,cAAc,GAAG,CAAC,CAAC;QACzB,KAAK,CAAC,eAAe,GAAG,CAAC,CAAC;QAC1B,KAAK,CAAC,eAAe,GAAG,CAAC,CAAC;QAC1B,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC;QAC5B,KAAK,CAAC,gBAAgB,GAAG,EAAE,CAAC;QAC5B,KAAK,CAAC,qBAAqB,GAAG,EAAE,CAAC;QACjC,KAAK,CAAC,kBAAkB,GAAG,IAAI,CAAC,WAAW,CAAC;QAC5C,4DAA4D;QAC5D,gEAAgE;QAChE,4DAA4D;QAC5D,2DAA2D;QAC3D,2DAA2D;QAC3D,6DAA6D;QAC7D,gCAAgC;QAChC,KAAK,CAAC,YAAY,GAAG,EAAE,CAAC;QACxB,KAAK,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC;QAC7C,KAAK,CAAC,aAAa,GAAG,SAAS,CAAC;QAChC,KAAK,CAAC,YAAY,GAAG,EAAE,CAAC;QAExB,IAAA,wBAAS,EAAC,KAAK,EAAE,iCAAiC,EAAE;YAClD,SAAS,EAAE,CAAC;YACZ,UAAU,EAAE,IAAI,CAAC,OAAO;SACzB,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC;AAnED,wCAmEC"}
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ /**
3
+ * toolCalls — pausable handler for executing the LLM-requested tool
4
+ * calls in the agent's ReAct loop.
5
+ *
6
+ * • `execute` iterates `scope.llmLatestToolCalls`, dispatches each
7
+ * tool, appends results to scope.history, and increments
8
+ * `scope.iteration`. If a tool throws `PauseRequest` (via
9
+ * `pauseHere()`), commits partial state and returns the pause
10
+ * payload so footprintjs captures a checkpoint.
11
+ * • `resume` runs after the consumer supplies the human's answer.
12
+ * Treats that answer as the paused tool's result, appends to
13
+ * history, then continues the ReAct iteration loop.
14
+ *
15
+ * Dispatch resolution order:
16
+ * 1. Static registry built at chart-build time (registryByName).
17
+ * 2. External `ToolProvider.list(ctx).find(...)` if a `.toolProvider()`
18
+ * was wired and the tool isn't in the static registry.
19
+ *
20
+ * Permission gate (when `permissionChecker` is configured) runs BEFORE
21
+ * `tool.execute`. Deny → tool not executed; result is a synthetic
22
+ * denial string. Allow / gate_open → execution proceeds.
23
+ *
24
+ * `read_skill` is the auto-attached activation tool — when the LLM
25
+ * calls it with a valid Skill id, the next InjectionEngine pass
26
+ * activates that Skill (lifetime: turn).
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.buildToolCallsHandler = void 0;
30
+ const typedEmit_js_1 = require("../../../recorders/core/typedEmit.js");
31
+ const pause_js_1 = require("../../pause.js");
32
+ const validators_js_1 = require("../validators.js");
33
+ /**
34
+ * Build the pausable tool-call handler for the agent's chart.
35
+ */
36
+ function buildToolCallsHandler(deps) {
37
+ const { registryByName, externalToolProvider, permissionChecker } = deps;
38
+ return {
39
+ execute: async (scope) => {
40
+ const toolCalls = scope.llmLatestToolCalls;
41
+ const iteration = scope.iteration;
42
+ const newHistory = [...scope.history];
43
+ // ALWAYS push the assistant turn when there are tool calls — even
44
+ // if the content was empty — so providers (Anthropic, OpenAI) can
45
+ // round-trip the tool_use blocks via `LLMMessage.toolCalls`.
46
+ // Without this, the next iteration's request lacks the assistant
47
+ // turn that initiated the tool call, and the API rejects the
48
+ // following tool_result with "preceding tool_use missing".
49
+ if (scope.llmLatestContent || toolCalls.length > 0) {
50
+ newHistory.push({
51
+ role: 'assistant',
52
+ content: scope.llmLatestContent ?? '',
53
+ ...(toolCalls.length > 0 && { toolCalls }),
54
+ });
55
+ }
56
+ // Resolve a tool by name, consulting the external ToolProvider
57
+ // if one was wired via `.toolProvider()` and the static
58
+ // registry doesn't carry the tool. The provider sees the same
59
+ // ctx the Tools slot used, so dispatch + visibility stay
60
+ // consistent within the iteration.
61
+ const lookupTool = (toolName) => {
62
+ const fromRegistry = registryByName.get(toolName);
63
+ if (fromRegistry)
64
+ return fromRegistry;
65
+ if (!externalToolProvider)
66
+ return undefined;
67
+ const activatedIds = scope.activatedInjectionIds ?? [];
68
+ const identity = scope.runIdentity;
69
+ const ctx = {
70
+ iteration: scope.iteration,
71
+ ...(activatedIds.length > 0 && {
72
+ activeSkillId: activatedIds[activatedIds.length - 1],
73
+ }),
74
+ ...(identity && { identity }),
75
+ };
76
+ const visible = externalToolProvider.list(ctx);
77
+ return visible.find((t) => t.schema.name === toolName);
78
+ };
79
+ for (const tc of toolCalls) {
80
+ const tool = lookupTool(tc.name);
81
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.stream.tool_start', {
82
+ toolName: tc.name,
83
+ toolCallId: tc.id,
84
+ args: tc.args,
85
+ ...(toolCalls.length > 1 && { parallelCount: toolCalls.length }),
86
+ });
87
+ const startMs = Date.now();
88
+ let result;
89
+ let error;
90
+ // Permission gate — when a checker is configured, evaluate BEFORE
91
+ // executing the tool. Emits `permission.check` with the decision.
92
+ // On 'deny', the tool is not executed and its result is a
93
+ // synthetic denial string; on 'allow'/'gate_open', execution
94
+ // proceeds normally (the gate is informational — the consumer's
95
+ // checker is responsible for any gate-open side effects).
96
+ let denied = false;
97
+ if (permissionChecker) {
98
+ try {
99
+ const decision = await permissionChecker.check({
100
+ capability: 'tool_call',
101
+ actor: 'agent',
102
+ target: tc.name,
103
+ context: tc.args,
104
+ });
105
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.permission.check', {
106
+ capability: 'tool_call',
107
+ actor: 'agent',
108
+ target: tc.name,
109
+ result: decision.result,
110
+ ...(decision.policyRuleId !== undefined && { policyRuleId: decision.policyRuleId }),
111
+ ...(decision.rationale !== undefined && { rationale: decision.rationale }),
112
+ });
113
+ if (decision.result === 'deny') {
114
+ denied = true;
115
+ result = `[permission denied: ${decision.rationale ?? 'policy'}]`;
116
+ }
117
+ }
118
+ catch (permErr) {
119
+ // A checker that throws is treated as deny-by-default. The
120
+ // denial message records the thrown error so consumers can
121
+ // debug policy-adapter failures without losing the run.
122
+ denied = true;
123
+ const msg = permErr instanceof Error ? permErr.message : String(permErr);
124
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.permission.check', {
125
+ capability: 'tool_call',
126
+ actor: 'agent',
127
+ target: tc.name,
128
+ result: 'deny',
129
+ rationale: `permission-checker threw: ${msg}`,
130
+ });
131
+ result = `[permission denied: checker error: ${msg}]`;
132
+ }
133
+ }
134
+ if (!denied) {
135
+ try {
136
+ if (!tool)
137
+ throw new Error(`Unknown tool: ${tc.name}`);
138
+ result = await tool.execute(tc.args, {
139
+ toolCallId: tc.id,
140
+ iteration,
141
+ });
142
+ }
143
+ catch (err) {
144
+ if ((0, pause_js_1.isPauseRequest)(err)) {
145
+ // Commit partial state so resume() can find history intact.
146
+ scope.history = newHistory;
147
+ scope.pausedToolCallId = tc.id;
148
+ scope.pausedToolName = tc.name;
149
+ scope.pausedToolStartMs = startMs;
150
+ // Returning a defined value triggers footprintjs pause —
151
+ // the returned object becomes the checkpoint's pauseData.
152
+ return {
153
+ toolCallId: tc.id,
154
+ toolName: tc.name,
155
+ ...(typeof err.data === 'object' && err.data !== null
156
+ ? err.data
157
+ : { data: err.data }),
158
+ };
159
+ }
160
+ error = true;
161
+ result = err instanceof Error ? err.message : String(err);
162
+ }
163
+ }
164
+ const durationMs = Date.now() - startMs;
165
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.stream.tool_end', {
166
+ toolCallId: tc.id,
167
+ result,
168
+ durationMs,
169
+ ...(error === true && { error: true }),
170
+ });
171
+ const resultStr = typeof result === 'string' ? result : (0, validators_js_1.safeStringify)(result);
172
+ newHistory.push({
173
+ role: 'tool',
174
+ content: resultStr,
175
+ toolCallId: tc.id,
176
+ toolName: tc.name,
177
+ });
178
+ // ── Dynamic ReAct wiring ───────────────────────────────
179
+ //
180
+ // (1) `lastToolResult` drives `on-tool-return` Injection
181
+ // triggers — the InjectionEngine's NEXT pass will see
182
+ // this and activate any matching Instructions.
183
+ scope.lastToolResult = { toolName: tc.name, result: resultStr };
184
+ // (2) `read_skill` is the auto-attached activation tool.
185
+ // When the LLM calls it with a valid Skill id, append
186
+ // to `activatedInjectionIds` so the InjectionEngine's
187
+ // NEXT pass activates that Skill (lifetime: turn — stays
188
+ // active until the turn ends).
189
+ if (tc.name === 'read_skill' && !error && !denied) {
190
+ const requestedId = tc.args.id;
191
+ if (typeof requestedId === 'string' && requestedId.length > 0) {
192
+ const current = scope.activatedInjectionIds;
193
+ if (!current.includes(requestedId)) {
194
+ scope.activatedInjectionIds = [...current, requestedId];
195
+ }
196
+ }
197
+ }
198
+ }
199
+ scope.history = newHistory;
200
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.agent.iteration_end', {
201
+ turnIndex: 0,
202
+ iterIndex: iteration,
203
+ toolCallCount: toolCalls.length,
204
+ history: scope.history,
205
+ });
206
+ scope.iteration = iteration + 1;
207
+ return undefined; // explicit: no pause, flow continues to loopTo
208
+ },
209
+ resume: (scope, input) => {
210
+ // Consumer-supplied resume input becomes the paused tool's result.
211
+ // The subflow's pre-pause scope is restored automatically by
212
+ // footprintjs 4.17.0 via `checkpoint.subflowStates`, so
213
+ // `scope.history` and `scope.pausedToolCallId` read back cleanly
214
+ // across same-executor AND cross-executor resume.
215
+ const toolCallId = scope.pausedToolCallId;
216
+ const toolName = scope.pausedToolName;
217
+ const startMs = scope.pausedToolStartMs;
218
+ const resultStr = typeof input === 'string' ? input : (0, validators_js_1.safeStringify)(input);
219
+ const newHistory = [
220
+ ...scope.history,
221
+ {
222
+ role: 'tool',
223
+ content: resultStr,
224
+ toolCallId,
225
+ toolName,
226
+ },
227
+ ];
228
+ scope.history = newHistory;
229
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.stream.tool_end', {
230
+ toolCallId,
231
+ result: input,
232
+ durationMs: Date.now() - startMs,
233
+ });
234
+ const iteration = scope.iteration;
235
+ (0, typedEmit_js_1.typedEmit)(scope, 'agentfootprint.agent.iteration_end', {
236
+ turnIndex: 0,
237
+ iterIndex: iteration,
238
+ toolCallCount: 1,
239
+ history: scope.history,
240
+ });
241
+ scope.iteration = iteration + 1;
242
+ // Clear pause checkpoint fields.
243
+ scope.pausedToolCallId = '';
244
+ scope.pausedToolName = '';
245
+ scope.pausedToolStartMs = 0;
246
+ },
247
+ };
248
+ }
249
+ exports.buildToolCallsHandler = buildToolCallsHandler;
250
+ //# sourceMappingURL=toolCalls.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolCalls.js","sourceRoot":"","sources":["../../../../src/core/agent/stages/toolCalls.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;AAKH,uEAAiE;AAEjE,6CAAgD;AAEhD,oDAAiD;AAkBjD;;GAEG;AACH,SAAgB,qBAAqB,CACnC,IAA0B;IAE1B,MAAM,EAAE,cAAc,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC;IAEzE,OAAO;QACL,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;YACvB,MAAM,SAAS,GAAG,KAAK,CAAC,kBAIrB,CAAC;YACJ,MAAM,SAAS,GAAG,KAAK,CAAC,SAAmB,CAAC;YAC5C,MAAM,UAAU,GAAiB,CAAC,GAAI,KAAK,CAAC,OAAiC,CAAC,CAAC;YAC/E,kEAAkE;YAClE,kEAAkE;YAClE,6DAA6D;YAC7D,iEAAiE;YACjE,6DAA6D;YAC7D,2DAA2D;YAC3D,IAAI,KAAK,CAAC,gBAAgB,IAAI,SAAS,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AAC;YACpD,MAAM,QAAQ,GAAG,KAAK,CAAC,cAAwB,CAAC;YAChD,MAAM,OAAO,GAAG,KAAK,CAAC,iBAA2B,CAAC;YAClD,MAAM,SAAS,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,6BAAa,EAAC,KAAK,CAAC,CAAC;YAC3E,MAAM,UAAU,GAAiB;gBAC/B,GAAI,KAAK,CAAC,OAAiC;gBAC3C;oBACE,IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,SAAS;oBAClB,UAAU;oBACV,QAAQ;iBACT;aACF,CAAC;YACF,KAAK,CAAC,OAAO,GAAG,UAAU,CAAC;YAE3B,IAAA,wBAAS,EAAC,KAAK,EAAE,gCAAgC,EAAE;gBACjD,UAAU;gBACV,MAAM,EAAE,KAAK;gBACb,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO;aACjC,CAAC,CAAC;YACH,MAAM,SAAS,GAAG,KAAK,CAAC,SAAmB,CAAC;YAC5C,IAAA,wBAAS,EAAC,KAAK,EAAE,oCAAoC,EAAE;gBACrD,SAAS,EAAE,CAAC;gBACZ,SAAS,EAAE,SAAS;gBACpB,aAAa,EAAE,CAAC;gBAChB,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;YACH,KAAK,CAAC,SAAS,GAAG,SAAS,GAAG,CAAC,CAAC;YAChC,iCAAiC;YACjC,KAAK,CAAC,gBAAgB,GAAG,EAAE,CAAC;YAC5B,KAAK,CAAC,cAAc,GAAG,EAAE,CAAC;YAC1B,KAAK,CAAC,iBAAiB,GAAG,CAAC,CAAC;QAC9B,CAAC;KACF,CAAC;AACJ,CAAC;AA7ND,sDA6NC"}
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ /**
3
+ * Agent type definitions — both PUBLIC types (AgentOptions, AgentInput,
4
+ * AgentOutput) consumed by `Agent.create({...}).run({...})` callers AND
5
+ * the INTERNAL `AgentState` shape used by stage functions.
6
+ *
7
+ * These were originally inline in `core/Agent.ts`; extracted here as
8
+ * part of the v2.11.1 decomposition. `core/Agent.ts` re-exports them
9
+ * for back-compat (the 28+ existing import sites continue to work).
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/agent/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG"}
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ /**
3
+ * Agent validators — pure helper functions extracted from Agent.ts.
4
+ *
5
+ * These run at Agent construction time (eagerly, so misconfiguration
6
+ * fails fast at `.build()`) and during stage execution (safeStringify
7
+ * for tool-result formatting).
8
+ *
9
+ * Pure functions, no class state — extracted for readability and
10
+ * isolated testability. The Agent class imports + invokes these in
11
+ * its constructor and stage handlers.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.safeStringify = exports.validateToolNameUniqueness = exports.clampIterations = exports.validateMemoryIdUniqueness = void 0;
15
+ /**
16
+ * Validate that every memory definition has a unique id. Each memory
17
+ * writes to its own scope key (`memoryInjection_${id}`); duplicates
18
+ * silently overwrite, leading to data loss that's hard to debug.
19
+ *
20
+ * Throws on collision so `Agent.build()` fails fast at construction.
21
+ */
22
+ function validateMemoryIdUniqueness(memories) {
23
+ const seen = new Set();
24
+ for (const m of memories) {
25
+ if (seen.has(m.id)) {
26
+ throw new Error(`Agent: duplicate memory id '${m.id}'. Each memory needs a unique id to keep ` +
27
+ 'its scope key (`memoryInjection_${id}`) collision-free.');
28
+ }
29
+ seen.add(m.id);
30
+ }
31
+ }
32
+ exports.validateMemoryIdUniqueness = validateMemoryIdUniqueness;
33
+ /**
34
+ * Clamp `maxIterations` to a safe range. The lower bound (1) prevents
35
+ * a 0-iteration agent (no LLM calls = no work); the upper bound (50)
36
+ * prevents runaway loops in misconfigured agents.
37
+ */
38
+ function clampIterations(n) {
39
+ if (!Number.isInteger(n) || n < 1)
40
+ return 1;
41
+ if (n > 50)
42
+ return 50;
43
+ return n;
44
+ }
45
+ exports.clampIterations = clampIterations;
46
+ /**
47
+ * Validate tool-name uniqueness across `.tool()`-registered tools +
48
+ * every Skill's `inject.tools[]`. The LLM dispatches by `tool.schema.name`
49
+ * (the wire format), so any collision silently shadows execution.
50
+ *
51
+ * Called eagerly in the Agent constructor so `Agent.build()` throws
52
+ * immediately, not on first `run()`.
53
+ *
54
+ * `read_skill` is reserved when ≥1 Skill is registered — collisions
55
+ * with consumer tools throw.
56
+ */
57
+ function validateToolNameUniqueness(registry, injections) {
58
+ // Static registry: unique within itself. The Agent.tool() builder
59
+ // method already throws on per-call duplicates; this is the
60
+ // belt-and-suspenders check at build time.
61
+ const staticNames = new Set();
62
+ for (const entry of registry) {
63
+ if (staticNames.has(entry.name)) {
64
+ throw new Error(`Agent: duplicate tool name '${entry.name}' in .tool() registry. ` +
65
+ `Tool names must be unique within the static registry.`);
66
+ }
67
+ staticNames.add(entry.name);
68
+ }
69
+ // `read_skill` is reserved when any Skill is registered. Collisions
70
+ // with consumer-supplied tools break the auto-attach path.
71
+ const skills = injections.filter((i) => i.flavor === 'skill');
72
+ if (skills.length > 0 && staticNames.has('read_skill')) {
73
+ throw new Error(`Agent: tool name 'read_skill' is reserved when ≥1 Skill is registered. ` +
74
+ `Rename your custom 'read_skill' tool or unregister it.`);
75
+ }
76
+ // Per-skill check: a skill's `inject.tools` array must be internally
77
+ // unique (no duplicate names within the same skill — that's a
78
+ // skill authoring bug). Across skills, sharing a Tool reference is
79
+ // EXPECTED and supported — common tools (e.g., a `flogi_lookup`
80
+ // used by multiple investigation skills) appear in multiple skills'
81
+ // tool arrays. Only one skill is active at a time (or, when several
82
+ // are active, deduped by name + reference at runtime). Sharing the
83
+ // same Tool object across skills is the supported pattern; sharing
84
+ // a Tool NAME with a DIFFERENT execute function is the actual bug —
85
+ // we detect that here too.
86
+ const seenByName = new Map();
87
+ for (const skill of skills) {
88
+ const intraSkill = new Set();
89
+ for (const tool of skill.inject.tools ?? []) {
90
+ const name = tool.schema.name;
91
+ if (intraSkill.has(name)) {
92
+ throw new Error(`Agent: skill '${skill.id}' lists tool '${name}' more than once in its ` +
93
+ `inject.tools array. Each skill's tools must be unique within itself.`);
94
+ }
95
+ intraSkill.add(name);
96
+ // Skill tools collide with the static .tool() registry → ambiguous dispatch
97
+ if (staticNames.has(name)) {
98
+ throw new Error(`Agent: skill '${skill.id}' tool '${name}' collides with the static .tool() ` +
99
+ `registry. Either rename the skill's tool or remove the static registration.`);
100
+ }
101
+ // Same name across skills with DIFFERENT Tool objects = ambiguous when
102
+ // both skills active. Same name + SAME Tool reference = supported sharing.
103
+ const prior = seenByName.get(name);
104
+ if (prior && prior !== tool) {
105
+ throw new Error(`Agent: tool name '${name}' is declared by multiple skills with different ` +
106
+ `Tool implementations. Skills MAY share the SAME Tool reference across ` +
107
+ `their inject.tools arrays (deduped at dispatch); they may NOT register ` +
108
+ `different functions under the same name (ambiguous dispatch).`);
109
+ }
110
+ seenByName.set(name, tool);
111
+ }
112
+ }
113
+ }
114
+ exports.validateToolNameUniqueness = validateToolNameUniqueness;
115
+ /**
116
+ * JSON.stringify with circular-ref protection. Tool results are untrusted —
117
+ * a hostile/buggy tool returning a cyclic object must not crash the run.
118
+ * Falls back to '[unstringifiable: <reason>]' so the LLM still sees that
119
+ * the tool ran and produced something unusable.
120
+ */
121
+ function safeStringify(value) {
122
+ try {
123
+ return JSON.stringify(value);
124
+ }
125
+ catch (err) {
126
+ const reason = err instanceof Error ? err.message : String(err);
127
+ return `[unstringifiable: ${reason}]`;
128
+ }
129
+ }
130
+ exports.safeStringify = safeStringify;
131
+ //# sourceMappingURL=validators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validators.js","sourceRoot":"","sources":["../../../src/core/agent/validators.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAMH;;;;;;GAMG;AACH,SAAgB,0BAA0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