@noetic-tools/core 5.21.0 → 5.22.0-next.1

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 (83) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.js +8 -0
  30. package/dist/harness/model-rounds.d.ts +30 -0
  31. package/dist/harness/model-rounds.js +146 -1
  32. package/dist/harness/model-tool-round.d.ts +3 -0
  33. package/dist/harness/model-tool-round.js +201 -19
  34. package/dist/harness/park-watchers.d.ts +93 -0
  35. package/dist/harness/park-watchers.js +217 -0
  36. package/dist/harness/read-decision.d.ts +23 -0
  37. package/dist/harness/read-decision.js +100 -0
  38. package/dist/harness/spend.js +4 -0
  39. package/dist/harness/steer-inbox.js +3 -1
  40. package/dist/harness/thread-record.d.ts +77 -1
  41. package/dist/harness/thread-record.js +272 -13
  42. package/dist/index.d.ts +17 -7
  43. package/dist/index.js +10 -2
  44. package/dist/interpreter/acp-resume.d.ts +77 -0
  45. package/dist/interpreter/acp-resume.js +164 -0
  46. package/dist/interpreter/acp-tools.d.ts +11 -0
  47. package/dist/interpreter/acp-tools.js +94 -7
  48. package/dist/interpreter/connection-steps.d.ts +24 -1
  49. package/dist/interpreter/connection-steps.js +77 -2
  50. package/dist/interpreter/execute-acp-agent.js +111 -15
  51. package/dist/interpreter/execute-action.js +7 -0
  52. package/dist/interpreter/execute-call.js +30 -4
  53. package/dist/interpreter/execute-control.js +21 -0
  54. package/dist/interpreter/execute-invoke-tool.js +149 -5
  55. package/dist/interpreter/execute-wait.js +67 -9
  56. package/dist/interpreter/execute.js +4 -0
  57. package/dist/interpreter/turn-ending.d.ts +15 -0
  58. package/dist/interpreter/turn-ending.js +46 -0
  59. package/dist/portable/builders.d.ts +1 -1
  60. package/dist/portable/builders.js +1 -1
  61. package/dist/runtime/durable/parking.d.ts +61 -0
  62. package/dist/runtime/durable/parking.js +137 -0
  63. package/dist/runtime/durable/session-store.d.ts +38 -0
  64. package/dist/runtime/durable/session-store.js +79 -1
  65. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  66. package/dist/runtime/durable/step-ledger.js +352 -15
  67. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  68. package/dist/runtime/durable/turn-lease.js +307 -0
  69. package/dist/runtime/held-calls.d.ts +192 -0
  70. package/dist/runtime/held-calls.js +496 -0
  71. package/dist/runtime/in-memory-storage.d.ts +10 -1
  72. package/dist/runtime/in-memory-storage.js +20 -2
  73. package/dist/runtime/message-queue.d.ts +2 -0
  74. package/dist/runtime/message-queue.js +8 -0
  75. package/dist/runtime/session-runner.d.ts +18 -2
  76. package/dist/runtime/session-runner.js +88 -3
  77. package/dist/runtime/tool-approval.d.ts +46 -6
  78. package/dist/runtime/tool-approval.js +160 -38
  79. package/dist/runtime/tool-call.d.ts +34 -2
  80. package/dist/runtime/tool-call.js +182 -13
  81. package/dist/runtime/tool-context.d.ts +15 -1
  82. package/dist/runtime/tool-context.js +38 -2
  83. package/package.json +3 -3
package/dist/index.d.ts CHANGED
@@ -47,7 +47,7 @@ export type { CallInput, CallModelOpts, CallOpName, CallOpts, CallOutput, Invoke
47
47
  /** @public */
48
48
  export { callModel, invokeTool, runCode, step } from './builders/step-builders.js';
49
49
  /** @public */
50
- export { tool, toolWithGenerator } from './builders/tool-builder.js';
50
+ export { hold, tool, toolWithGenerator } from './builders/tool-builder.js';
51
51
  /** @public */
52
52
  export type { VerifyConnectionRef, VerifyEachOutput, VerifyMatcherLike, VerifyOpts, } from './builders/verify-builder.js';
53
53
  /** @public */
@@ -68,12 +68,14 @@ export { aiCondition, allCondition, anyCondition, embeddingMatch, otherwise, sem
68
68
  export { cosineSimilarity } from './conditions/cosine-similarity.js';
69
69
  /** @public */
70
70
  /** @public */
71
- export { isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
71
+ export { DECISION_ITEM_TYPE, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
72
72
  /** @public */
73
73
  export type { AskUserAnnotation, AskUserInput, AskUserOption, AskUserOutput, AskUserQuestion, } from './types/ask-user-types.js';
74
74
  /** @public */
75
75
  export { AskUserAnnotationSchema, AskUserInputSchema, AskUserOptionSchema, AskUserOutputSchema, AskUserQuestionSchema, } from './types/ask-user-types.js';
76
76
  /** @public */
77
+ export { ACP_RESUME_NOTICE } from './interpreter/acp-resume.js';
78
+ /** @public */
77
79
  export { execute } from './interpreter/execute.js';
78
80
  /** @public */
79
81
  /** @public */
@@ -102,6 +104,8 @@ export { GenAI, NoeticAttr, NoeticEvent, ToolAttr } from './observability/genai-
102
104
  /** @public */
103
105
  export { InMemoryExporter, NoopExporter } from './observability/trace-exporter.js';
104
106
  /** @public */
107
+ export type { CreateInMemoryStorageOptions } from './runtime/in-memory-storage.js';
108
+ /** @public */
105
109
  export { createInMemoryStorage } from './runtime/in-memory-storage.js';
106
110
  /** @public */
107
111
  export type { DynamicWorkflowOpts, ParseAndRunWorkflowOpts } from './builders/dynamic-workflow.js';
@@ -114,12 +118,18 @@ export { DEFAULT_EXPRESSION_LIMITS } from './expression/jsonata.js';
114
118
  /** @public */
115
119
  export { AgentHarness } from './harness/agent-harness.js';
116
120
  /** @public */
117
- export type { AgentEnvironmentConfig, StorageEnvironmentConfig, } from './harness/harness-options.js';
121
+ export type { AgentEnvironmentConfig, ParkConfig, StorageEnvironmentConfig, TurnLeaseConfig, WakeTimeListener, } from './harness/harness-options.js';
122
+ /** @public */
123
+ export { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS } from './harness/park-watchers.js';
118
124
  /** @public */
119
125
  export type { AfterFirstTurnContext, CheckpointStore, CreateCheckpointStoreOptions, CreateNudgeMessageOpts, DetachedSignal, RunnableLoopHarness, RunnableLoopOpts, SessionSeedHarness, StallNudgeOpts, StepLedgerRetention, StepLedgerStats, } from './runtime/durable/index.js';
120
126
  /** @public */
121
127
  export { CheckpointKeys, createCheckpointStore, createDetachedSignal, createNudgeMessage, createStallNudgeHook, DEFAULT_NUDGE_MESSAGE_TEXT, DEFAULT_STEP_LEDGER_RETENTION, runnableLoop, seedFromItems, } from './runtime/durable/index.js';
122
128
  /** @public */
129
+ export { DEFAULT_PARK_GRACE_MS } from './runtime/durable/parking.js';
130
+ /** @public */
131
+ export { DEFAULT_LEASE_TTL_MS } from './runtime/durable/turn-lease.js';
132
+ /** @public */
123
133
  export { getRegistry, lookupStep, registerStep } from './runtime/step-registry.js';
124
134
  /** @public */
125
135
  export type { Expression } from '@noetic-tools/types';
@@ -156,7 +166,7 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
156
166
  /** @public */
157
167
  export type { NoeticError } from '@noetic-tools/types';
158
168
  /** @public */
159
- export type { ContentPart, DeveloperMessageExtensionItem, ExecuteInput, ExtendedItem, ExtensionItem, FileSearchItem, FunctionCallItem, FunctionCallOutputItem, ImageGenerationItem, InferExtendedItem, InputContentPart, InputFilePart, InputImagePart, InputMessageItem, InputTextPart, Item, ItemBase, ItemSchemaExtensions, MessageItem, OutputItem, OutputTextPart, ReasoningItem, ReasoningTextPart, RefusalPart, ServerToolItem, SummaryTextPart, WebSearchItem, } from '@noetic-tools/types';
169
+ export type { ContentPart, DecisionItem, DeveloperMessageExtensionItem, ExecuteArgument, ExecuteInput, ExtendedItem, ExtensionItem, FileSearchItem, FunctionCallItem, FunctionCallOutputItem, ImageGenerationItem, InferExtendedItem, InputContentPart, InputFilePart, InputImagePart, InputMessageItem, InputTextPart, Item, ItemBase, ItemSchemaExtensions, MessageItem, OutputItem, OutputTextPart, ReasoningItem, ReasoningTextPart, RefusalPart, ServerToolItem, SummaryTextPart, WebSearchItem, } from '@noetic-tools/types';
160
170
  /** @public */
161
171
  export type { BudgetConfig, CompleteParams, ContextConfig, ContextData, ContextLayer, ContextLayerHooks, DisposeParams, InferContext, InferContextShape, InitParams, InitResult, LayerDataDecl, LayerFunctionDecl, LayerPlacement, LayerProvides, LayerTimeouts, ParentUpdateParams, ParentUpdateResult, ProjectionPolicy, RecallParams, RecallResult, RenderDeltaParams, ReturnParams, ReturnResult, ScopedStorage, SpawnParams, SpawnResult, StorageAdapter, StoreParams, StoreResult, } from '@noetic-tools/context';
162
172
  /** @public */
@@ -168,13 +178,13 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
168
178
  /** @public */
169
179
  export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
170
180
  /** @public */
171
- export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
181
+ export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldResolution, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
172
182
  /** @public */
173
183
  export type { PendingSpend, ReconcileSpendOptions, SpendSettlement, WriteOffSpendOptions, } from '@noetic-tools/types';
174
184
  /** @public */
175
185
  export { SpendKind } from '@noetic-tools/types';
176
186
  /** @public */
177
- export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
187
+ export type { AfterModelCallParams, AfterModelCallResult, ApproveRequest, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
178
188
  /** @public */
179
189
  export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
180
190
  /** @public */
@@ -205,7 +215,7 @@ export { createLiveHandles } from './adapters/live-handles.js';
205
215
  /** @public */
206
216
  export type { ToolContext, ToolExecutionContext } from '@noetic-tools/types';
207
217
  /** @public */
208
- export type { ArtifactLink, ArtifactMeta, ArtifactRecord, ArtifactRetention, ArtifactStore, BlobRef, BlobRefBody, BlobReference, CallOptions, CallOutcome, CallResult, Connection, ConnectionAllowlist, ConnectionAllowlistEntry, ConnectionConfig, ConnectionEntries, ConnectionEntry, ConnectionEvent, ConnectionEventInfo, ConnectionEventInit, ConnectionExpose, ConnectionHandle, ConnectionHandleOptions, ConnectionIdentity, ConnectionLease, ConnectionLook, ConnectionManifest, ConnectionMissing, ConnectionOperationAnnotations, ConnectionOperationInfo, ConnectionPick, ConnectionPolicy, ConnectionPoolConfig, ConnectionProvider, ConnectionRequirement, ConnectionResourceInfo, ConnectionSource, ConnectionState, ConnectionStatus, ConnectionsConfig, ConnectionTaskStatus, ConnectionTasks, ConnectionTrigger, ConnectOptions, CronOptions, CronTick, Determinism, EventStream, EventStreamMessage, FreshScope, GrantedMcpServer, ListenRequest, Locator, McpAllowlist, McpCommandGrant, McpNamedValue, McpUrlGrant, Receipt, Ref, RefBody, Secret, SecretResolver, SourceDefinition, SourceEmitEvent, Target, } from '@noetic-tools/types';
218
+ export type { ArtifactLink, ArtifactMeta, ArtifactRecord, ArtifactRetention, ArtifactStore, BlobRef, BlobRefBody, BlobReference, CallOptions, CallOutcome, CallResult, Connection, ConnectionAllowlist, ConnectionAllowlistEntry, ConnectionConfig, ConnectionEntries, ConnectionEntry, ConnectionEvent, ConnectionEventInfo, ConnectionEventInit, ConnectionExpose, ConnectionHandle, ConnectionHandleOptions, ConnectionIdentity, ConnectionLease, ConnectionLook, ConnectionManifest, ConnectionMissing, ConnectionOperationAnnotations, ConnectionOperationInfo, ConnectionPick, ConnectionPolicy, ConnectionPoolConfig, ConnectionProvider, ConnectionRequirement, ConnectionResourceInfo, ConnectionSource, ConnectionState, ConnectionStatus, ConnectionsConfig, ConnectionTaskStatus, ConnectionTasks, ConnectionTrigger, ConnectOptions, CronOptions, CronTick, Determinism, EventSchedule, EventStream, EventStreamMessage, FreshScope, GrantedMcpServer, ListenRequest, Locator, McpAllowlist, McpCommandGrant, McpNamedValue, McpUrlGrant, Receipt, Ref, RefBody, Secret, SecretResolver, SourceDefinition, SourceEmitEvent, Target, } from '@noetic-tools/types';
209
219
  /** @public */
210
220
  /** @public */
211
221
  export { ARTIFACT_URI_PREFIX, artifactDigest, artifactUri, ConnectionUnsatisfiedError, DEFAULT_ARTIFACT_MAX_BYTES_PER_RUN, DEFAULT_ARTIFACT_MAX_COUNT_PER_RUN, isBlobRef, isConnectionEntry, isConnectionPick, isConnectionUnsatisfiedError, isRef, isSecret, refId, secret, } from '@noetic-tools/types';
package/dist/index.js CHANGED
@@ -36,7 +36,7 @@ export { spawn } from './builders/spawn-builder.js';
36
36
  /** @public */
37
37
  export { callModel, invokeTool, runCode, step } from './builders/step-builders.js';
38
38
  /** @public */
39
- export { tool, toolWithGenerator } from './builders/tool-builder.js';
39
+ export { hold, tool, toolWithGenerator } from './builders/tool-builder.js';
40
40
  /** @public */
41
41
  export { verify } from './builders/verify-builder.js';
42
42
  /** @public */
@@ -51,12 +51,14 @@ export { cosineSimilarity } from './conditions/cosine-similarity.js';
51
51
  //#region Errors
52
52
  /** @public */
53
53
  /** @public */
54
- export { isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
54
+ export { DECISION_ITEM_TYPE, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
55
55
  /** @public */
56
56
  export { AskUserAnnotationSchema, AskUserInputSchema, AskUserOptionSchema, AskUserOutputSchema, AskUserQuestionSchema, } from './types/ask-user-types.js';
57
57
  //#endregion
58
58
  //#region Execution
59
59
  /** @public */
60
+ export { ACP_RESUME_NOTICE } from './interpreter/acp-resume.js';
61
+ /** @public */
60
62
  export { execute } from './interpreter/execute.js';
61
63
  /** @public */
62
64
  /** @public */
@@ -92,8 +94,14 @@ export { DEFAULT_EXPRESSION_LIMITS } from './expression/jsonata.js';
92
94
  /** @public */
93
95
  export { AgentHarness } from './harness/agent-harness.js';
94
96
  /** @public */
97
+ export { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS } from './harness/park-watchers.js';
98
+ /** @public */
95
99
  export { CheckpointKeys, createCheckpointStore, createDetachedSignal, createNudgeMessage, createStallNudgeHook, DEFAULT_NUDGE_MESSAGE_TEXT, DEFAULT_STEP_LEDGER_RETENTION, runnableLoop, seedFromItems, } from './runtime/durable/index.js';
96
100
  /** @public */
101
+ export { DEFAULT_PARK_GRACE_MS } from './runtime/durable/parking.js';
102
+ /** @public */
103
+ export { DEFAULT_LEASE_TTL_MS } from './runtime/durable/turn-lease.js';
104
+ /** @public */
97
105
  export { getRegistry, lookupStep, registerStep } from './runtime/step-registry.js';
98
106
  /** @public */
99
107
  /** @public */
@@ -0,0 +1,77 @@
1
+ /**
2
+ * What an ACP step keeps so a resumed run can go on with the agent's own session
3
+ * instead of starting it over (spec 27 § Resuming a step).
4
+ *
5
+ * Two records, both beneath the step's place in the run:
6
+ *
7
+ * - The agent's session id, written when the step opens a session. A resumed step
8
+ * reloads that session (`session/load`) when the agent can.
9
+ * - Each tool call the agent made through the bridge, written as it finishes. A
10
+ * resumed agent that makes the same call again gets the recorded result.
11
+ */
12
+ import type { Context, ContextData, Tool } from '@noetic-tools/types';
13
+ import { z } from 'zod';
14
+ import type { ToolCallResult } from '../runtime/tool-call.js';
15
+ declare const AcpSessionRecordSchema: z.ZodObject<{
16
+ sessionId: z.ZodString;
17
+ agentId: z.ZodString;
18
+ }, z.core.$strip>;
19
+ /** The agent session a step opened, as stored. */
20
+ export type AcpSessionRecord = z.infer<typeof AcpSessionRecordSchema>;
21
+ /** The stored session of one step. */
22
+ export interface AcpSessionRecords {
23
+ load(): Promise<AcpSessionRecord | undefined>;
24
+ write(record: AcpSessionRecord): Promise<void>;
25
+ clear(): Promise<void>;
26
+ }
27
+ /** One bridged call's place in the step's records. */
28
+ export interface BridgedCallRecord {
29
+ /**
30
+ * The call's id for anything that must survive a resume: its held record, a
31
+ * durable tool's intent, its idempotency key. The agent's own id for the call
32
+ * changes when the agent makes it again.
33
+ */
34
+ readonly id: string;
35
+ /** The result an earlier attempt of the step recorded for this call. */
36
+ take(): ToolCallResult | undefined;
37
+ /** Record what the call produced. Resolves whether the record was stored. */
38
+ store(result: ToolCallResult): Promise<boolean>;
39
+ }
40
+ /**
41
+ * @public
42
+ * What a resumed ACP step tells the agent before its prompt, when it reloaded the
43
+ * agent's session.
44
+ */
45
+ export declare const ACP_RESUME_NOTICE = "Your previous turn on this task was cut off before it finished. Continue the task below from where you stopped. Do not redo work that is already done.";
46
+ /**
47
+ * The session record of the ACP step running on `ctx`, or undefined when the run
48
+ * is not durable: no ledger, no storage, or no place in the run.
49
+ */
50
+ export declare function acpSessionRecords(ctx: Context<ContextData>): AcpSessionRecords | undefined;
51
+ /**
52
+ * Hands out the record of each bridged call of one step run. A call is known by
53
+ * its tool, its arguments, and its place among the calls with that tool and those
54
+ * arguments: a resumed agent's ids are new, but what it asks for is not.
55
+ */
56
+ export declare class BridgedCallRecords {
57
+ private readonly seen;
58
+ private reloaded;
59
+ /**
60
+ * The agent's session was reloaded: it has its own record of the calls it
61
+ * finished, and was told not to redo them. A call it makes now is a new call,
62
+ * even with a tool and arguments it used before, so it must not be answered
63
+ * from a record. Each call's order starts after the ones already recorded.
64
+ *
65
+ * An agent that starts over in a new session makes its calls again from the
66
+ * first, and those are answered from the record.
67
+ */
68
+ sessionReloaded(): void;
69
+ recordFor(opts: {
70
+ ctx: Context<ContextData>;
71
+ stepId: string;
72
+ tool: Tool | undefined;
73
+ wireName: string;
74
+ args: unknown;
75
+ }): BridgedCallRecord;
76
+ }
77
+ export {};
@@ -0,0 +1,164 @@
1
+ /**
2
+ * What an ACP step keeps so a resumed run can go on with the agent's own session
3
+ * instead of starting it over (spec 27 § Resuming a step).
4
+ *
5
+ * Two records, both beneath the step's place in the run:
6
+ *
7
+ * - The agent's session id, written when the step opens a session. A resumed step
8
+ * reloads that session (`session/load`) when the agent can.
9
+ * - Each tool call the agent made through the bridge, written as it finishes. A
10
+ * resumed agent that makes the same call again gets the recorded result.
11
+ */
12
+ import { frameworkCast } from '@noetic-tools/types';
13
+ import { z } from 'zod';
14
+ import { stepPathOf } from '../connections/durability.js';
15
+ import { ContextImpl } from '../runtime/context-impl.js';
16
+ import { hashStepInput } from '../runtime/durable/step-ledger.js';
17
+ import { pendingEntryKey, runRootOf } from './connection-steps.js';
18
+ //#region Types
19
+ const AcpSessionRecordSchema = z.object({
20
+ sessionId: z.string(),
21
+ agentId: z.string(),
22
+ });
23
+ const BridgedOutputSchema = z.object({
24
+ output: z.string(),
25
+ result: z.unknown().optional(),
26
+ error: z.boolean().optional(),
27
+ });
28
+ /** The kind of a bridged call's ledger entry. */
29
+ const BRIDGED_KIND = 'acp-tool';
30
+ /**
31
+ * @public
32
+ * What a resumed ACP step tells the agent before its prompt, when it reloaded the
33
+ * agent's session.
34
+ */
35
+ export const ACP_RESUME_NOTICE = 'Your previous turn on this task was cut off before it finished. Continue the task below from where you stopped. Do not redo work that is already done.';
36
+ function storageOf(ctx) {
37
+ return frameworkCast(ctx.harness).config?.storage;
38
+ }
39
+ function warn(action, key, error) {
40
+ console.warn(`acp step: failed to ${action} session record "${key}":`, error instanceof Error ? error.message : String(error));
41
+ }
42
+ //#endregion
43
+ //#region Public API
44
+ /**
45
+ * The session record of the ACP step running on `ctx`, or undefined when the run
46
+ * is not durable: no ledger, no storage, or no place in the run.
47
+ */
48
+ export function acpSessionRecords(ctx) {
49
+ const storage = storageOf(ctx);
50
+ const path = stepPathOf(ctx);
51
+ const ledger = ctx instanceof ContextImpl ? ctx.ledger : undefined;
52
+ if (!storage || !ledger || path === undefined) {
53
+ return undefined;
54
+ }
55
+ // With the run's pending entries, so clearing the run clears it.
56
+ const key = pendingEntryKey(runRootOf(ctx).id, `${path}/acp-session`);
57
+ return {
58
+ async load() {
59
+ const parsed = AcpSessionRecordSchema.safeParse(await storage.get(key));
60
+ return parsed.success ? parsed.data : undefined;
61
+ },
62
+ async write(record) {
63
+ if (!ledger.isHeld) {
64
+ return;
65
+ }
66
+ await storage.set(key, record).catch((error) => warn('write', key, error));
67
+ },
68
+ async clear() {
69
+ if (!ledger.isHeld) {
70
+ return;
71
+ }
72
+ await storage.delete(key).catch((error) => warn('clear', key, error));
73
+ },
74
+ };
75
+ }
76
+ /**
77
+ * Hands out the record of each bridged call of one step run. A call is known by
78
+ * its tool, its arguments, and its place among the calls with that tool and those
79
+ * arguments: a resumed agent's ids are new, but what it asks for is not.
80
+ */
81
+ export class BridgedCallRecords {
82
+ seen = new Map();
83
+ reloaded = false;
84
+ /**
85
+ * The agent's session was reloaded: it has its own record of the calls it
86
+ * finished, and was told not to redo them. A call it makes now is a new call,
87
+ * even with a tool and arguments it used before, so it must not be answered
88
+ * from a record. Each call's order starts after the ones already recorded.
89
+ *
90
+ * An agent that starts over in a new session makes its calls again from the
91
+ * first, and those are answered from the record.
92
+ */
93
+ sessionReloaded() {
94
+ this.reloaded = true;
95
+ }
96
+ recordFor(opts) {
97
+ const { ctx, stepId, tool, wireName } = opts;
98
+ const inputHash = hashStepInput({
99
+ name: wireName,
100
+ arguments: opts.args,
101
+ });
102
+ const step = stepPathOf(ctx) ?? stepId;
103
+ const call = `${wireName}:${inputHash ?? 'unhashed'}`;
104
+ const ledger = ctx instanceof ContextImpl ? ctx.ledger : undefined;
105
+ const pathAt = (n) => `${step}/bridged:${call}#${n}`;
106
+ const key = `${step}\u0000${call}`;
107
+ let order = this.seen.get(key);
108
+ if (order === undefined) {
109
+ order = 0;
110
+ // Past what a reloaded agent already finished: those are not coming again.
111
+ while (this.reloaded && ledger?.has(pathAt(order))) {
112
+ order += 1;
113
+ }
114
+ }
115
+ this.seen.set(key, order + 1);
116
+ const path = pathAt(order);
117
+ // `durable: false` records nothing; unhashable arguments cannot be matched.
118
+ const records = ledger !== undefined && tool?.durable !== false && inputHash !== undefined;
119
+ return {
120
+ id: `acp:${path}`,
121
+ take: () => {
122
+ if (!records) {
123
+ return undefined;
124
+ }
125
+ const entry = ledger.take(path, {
126
+ id: stepId,
127
+ kind: BRIDGED_KIND,
128
+ inputHash,
129
+ });
130
+ const parsed = entry ? BridgedOutputSchema.safeParse(entry.output) : undefined;
131
+ return parsed?.success ? parsed.data : undefined;
132
+ },
133
+ store: async (result) => {
134
+ if (!records || result.held !== undefined) {
135
+ return false;
136
+ }
137
+ if (tool?.durable === true) {
138
+ ledger.noteEffect(path);
139
+ }
140
+ return ledger.record({
141
+ path,
142
+ stepId,
143
+ kind: BRIDGED_KIND,
144
+ inputHash,
145
+ output: {
146
+ output: result.output,
147
+ ...(result.result === undefined
148
+ ? {}
149
+ : {
150
+ result: result.result,
151
+ }),
152
+ ...(result.error === undefined
153
+ ? {}
154
+ : {
155
+ error: result.error,
156
+ }),
157
+ },
158
+ completedAt: new Date().toISOString(),
159
+ });
160
+ },
161
+ };
162
+ }
163
+ }
164
+ //#endregion
@@ -61,6 +61,8 @@ export declare class AcpToolRunner implements AcpToolHost {
61
61
  private readonly announced;
62
62
  /** Ids already given to a call this session; an agent may not reuse one. */
63
63
  private readonly claimed;
64
+ /** What each call recorded, so a resumed step replays it (spec 27 § Resuming a step). */
65
+ private readonly records;
64
66
  constructor(source: ReadonlyArray<Tool>);
65
67
  /** Point the runner at the step whose turn is about to start. */
66
68
  bind(binding: AcpToolBinding): void;
@@ -72,6 +74,8 @@ export declare class AcpToolRunner implements AcpToolHost {
72
74
  * turn, as an in-flight `callModel` call belongs to its aborted round.
73
75
  */
74
76
  idle(): Promise<void>;
77
+ /** The agent's session was reloaded: see `BridgedCallRecords.sessionReloaded`. */
78
+ sessionReloaded(): void;
75
79
  /** The tool's wire name when `title` is how an agent titles a call to it. */
76
80
  wireNameOf(title: string): string | undefined;
77
81
  /** Note an agent `tool_call`, so a call without an id in `_meta` can take its id. */
@@ -90,6 +94,13 @@ export declare class AcpToolRunner implements AcpToolHost {
90
94
  private callIdFor;
91
95
  private announcedId;
92
96
  private unwrap;
97
+ /**
98
+ * Run the call to a result. A call held for a person waits here, with the agent
99
+ * waiting on it: the turn stays live, since the agent's process is what holds its
100
+ * place. The result is recorded before the call's intent or hold is dropped, so a
101
+ * step cut off in between asks again rather than runs again.
102
+ */
103
+ private settle;
93
104
  private execute;
94
105
  }
95
106
  /**
@@ -13,8 +13,10 @@ import { orderedCallId } from '../connections/durability.js';
13
13
  import { offeredTools, stepConnectionsOf } from '../connections/step-tools.js';
14
14
  import { ToolAttr } from '../observability/genai-attributes.js';
15
15
  import { drainsOf } from '../runtime/drain.js';
16
+ import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
16
17
  import { createToolResultItem, executeToolCall, resolveWireJsonSchema } from '../runtime/tool-call.js';
17
18
  import { sanitizeToolNameForWire } from '../util/tool-name.js';
19
+ import { BridgedCallRecords } from './acp-resume.js';
18
20
  import { openChildSpan, traceChild } from './child-span.js';
19
21
  import { deduplicateTools } from './collect-tools.js';
20
22
  import { resolveLazy, resolveToolsAndRestrictions, splitResolvedTools } from './execute-action.js';
@@ -169,6 +171,8 @@ export class AcpToolRunner {
169
171
  announced = new Map();
170
172
  /** Ids already given to a call this session; an agent may not reuse one. */
171
173
  claimed = new Set();
174
+ /** What each call recorded, so a resumed step replays it (spec 27 § Resuming a step). */
175
+ records = new BridgedCallRecords();
172
176
  constructor(source) {
173
177
  this.source = source;
174
178
  const wrapped = new Set();
@@ -218,6 +222,10 @@ export class AcpToolRunner {
218
222
  await settled;
219
223
  } while (settled !== this.queue);
220
224
  }
225
+ /** The agent's session was reloaded: see `BridgedCallRecords.sessionReloaded`. */
226
+ sessionReloaded() {
227
+ this.records.sessionReloaded();
228
+ }
221
229
  /** The tool's wire name when `title` is how an agent titles a call to it. */
222
230
  wireNameOf(title) {
223
231
  return this.tools.find((tool) => bridgedToolTitles(this.serverName, tool.name).includes(title))
@@ -344,21 +352,100 @@ export class AcpToolRunner {
344
352
  }
345
353
  return Reflect.get(call.args, WRAPPED_ARG);
346
354
  }
355
+ /**
356
+ * Run the call to a result. A call held for a person waits here, with the agent
357
+ * waiting on it: the turn stays live, since the agent's process is what holds its
358
+ * place. The result is recorded before the call's intent or hold is dropped, so a
359
+ * step cut off in between asks again rather than runs again.
360
+ */
361
+ async settle(binding, record, call) {
362
+ const { ctx } = binding;
363
+ const { params, signal } = call;
364
+ let result = await executeToolCall(params);
365
+ let announced;
366
+ while (result.held !== undefined) {
367
+ const { held } = result;
368
+ // Said once per question, under the id the agent's other events carry.
369
+ if (announced !== held.reason) {
370
+ announced = held.reason;
371
+ binding.events.toolEvent('tool_call_held', {
372
+ ...held,
373
+ callId: params.callId ?? held.callId,
374
+ heldAs: held.callId,
375
+ });
376
+ }
377
+ await waitOnHeldCalls({
378
+ harness: ctx.harness,
379
+ ctx,
380
+ callIds: [
381
+ held.callId,
382
+ ],
383
+ signal,
384
+ park: false,
385
+ });
386
+ // The agent stopped waiting for this call: nobody is left to give an answer to.
387
+ if (signal.aborted) {
388
+ if (mayWriteHolds(ctx)) {
389
+ await heldCallsOf(ctx.harness).close(heldScopeOf(ctx), held.callId);
390
+ }
391
+ return {
392
+ output: CANCELLED_OUTPUT,
393
+ error: true,
394
+ };
395
+ }
396
+ result = await executeToolCall(params);
397
+ }
398
+ const stored = await record.store(result);
399
+ if (!mayWriteHolds(ctx)) {
400
+ return result;
401
+ }
402
+ const holds = heldCallsOf(ctx.harness);
403
+ if (result.armed && stored) {
404
+ await holds.disarm(heldScopeOf(ctx), record.id);
405
+ }
406
+ if (result.settled) {
407
+ await holds.close(heldScopeOf(ctx), record.id);
408
+ }
409
+ return result;
410
+ }
347
411
  async execute(binding, call, callId, tool) {
348
412
  const args = this.unwrap(call);
349
413
  binding.events.toolEvent('tool_call_started', {
350
414
  name: call.name,
351
415
  callId,
352
416
  });
353
- const result = await executeToolCall({
354
- toolName: call.name,
417
+ const record = this.records.recordFor({
418
+ ctx: binding.ctx,
419
+ stepId: binding.stepId,
420
+ tool,
421
+ wireName: call.name,
355
422
  args,
356
- tools: this.source,
357
- context: binding.ctx,
358
- harness: binding.ctx.harness,
359
- layers: binding.layers,
360
- callId,
361
423
  });
424
+ const replayed = record.take();
425
+ if (replayed && mayWriteHolds(binding.ctx)) {
426
+ // A host that died after recording this result, and before dropping the call's
427
+ // intent or its answered hold, left them behind. The record says it is done.
428
+ const holds = heldCallsOf(binding.ctx.harness);
429
+ const executionId = heldScopeOf(binding.ctx);
430
+ await holds.disarm(executionId, record.id);
431
+ if (await holds.load(executionId, record.id)) {
432
+ await holds.close(executionId, record.id);
433
+ }
434
+ }
435
+ const result = replayed ??
436
+ (await this.settle(binding, record, {
437
+ signal: call.signal,
438
+ params: {
439
+ toolName: call.name,
440
+ args,
441
+ tools: this.source,
442
+ context: binding.ctx,
443
+ harness: binding.ctx.harness,
444
+ layers: binding.layers,
445
+ callId,
446
+ recordId: record.id,
447
+ },
448
+ }));
362
449
  const callItem = {
363
450
  id: callId,
364
451
  type: 'function_call',
@@ -49,6 +49,8 @@ declare const PendingEntrySchema: z.ZodObject<{
49
49
  leaseId: z.ZodOptional<z.ZodString>;
50
50
  cursor: z.ZodOptional<z.ZodNullable<z.ZodString>>;
51
51
  deadline: z.ZodOptional<z.ZodNumber>;
52
+ event: z.ZodOptional<z.ZodString>;
53
+ durable: z.ZodOptional<z.ZodBoolean>;
52
54
  }, z.core.$strip>;
53
55
  /**
54
56
  * The harness's connection registry.
@@ -135,12 +137,33 @@ export declare function refuseWitnessAct(ctx: Context, resolved: ResolvedConnect
135
137
  export declare class PendingEntries {
136
138
  private readonly storage;
137
139
  private readonly key;
138
- constructor(storage: StorageAdapter, key: string);
140
+ /** False once the run writes under a lease it no longer holds. */
141
+ private readonly mayWrite;
142
+ constructor(storage: StorageAdapter, key: string,
143
+ /** False once the run writes under a lease it no longer holds. */
144
+ mayWrite?: () => boolean);
139
145
  /** The entry a previous attempt left, or undefined when there is none (or it does not parse). */
140
146
  load(): Promise<PendingEntry | undefined>;
141
147
  write(entry: PendingEntry): Promise<void>;
142
148
  clear(): Promise<void>;
143
149
  }
150
+ /**
151
+ * The events an execution's waits listen for and can pick up again from a cursor:
152
+ * what a watcher needs to wake a parked turn (spec 23 § Parked turns).
153
+ */
154
+ export declare function resumableWaitsOf(storage: StorageAdapter, executionId: string): Promise<Array<{
155
+ connection: string;
156
+ event: string;
157
+ cursor: string | null;
158
+ }>>;
159
+ /**
160
+ * The long operations an execution's calls wait on: what a watcher polls to know
161
+ * when a parked turn can go on (spec 23 § Parked turns).
162
+ */
163
+ export declare function pendingTasksOf(storage: StorageAdapter, executionId: string): Promise<Array<{
164
+ connection: string;
165
+ taskId: string;
166
+ }>>;
144
167
  /** The storage key of a step's pending entry. */
145
168
  export declare function pendingEntryKey(executionId: string, ledgerKey: string): string;
146
169
  /**