@noetic-tools/core 5.22.0-next.6 → 5.22.0-next.7
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/builders/step-builders.d.ts +2 -0
- package/dist/builders/workflow-acp-grants.js +5 -0
- package/dist/builders/workflow-connection-nodes.js +1 -0
- package/dist/connections/harness-wiring.js +11 -2
- package/dist/index.d.ts +1 -1
- package/dist/interpreter/acp-questions.d.ts +30 -0
- package/dist/interpreter/acp-questions.js +153 -0
- package/dist/interpreter/acp-resume.d.ts +1 -0
- package/dist/interpreter/acp-resume.js +5 -0
- package/dist/interpreter/execute-acp-agent.js +172 -38
- package/dist/runtime/held-calls.d.ts +14 -0
- package/dist/runtime/held-calls.js +46 -7
- package/dist/runtime/held-question.d.ts +18 -0
- package/dist/runtime/held-question.js +179 -0
- package/package.json +2 -2
- package/schema/noetic-workflow.schema.json +7 -0
|
@@ -77,6 +77,8 @@ export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<T
|
|
|
77
77
|
permissions?: AcpPermissionPolicy;
|
|
78
78
|
/** Async resolver consulted when the policy and steering both abstain. */
|
|
79
79
|
onPermissionRequest?: AcpPermissionHandler;
|
|
80
|
+
/** Trusted instructions added to the agent's own system prompt, as `callModel`'s `instructions`. */
|
|
81
|
+
instructions?: Lazy<string | undefined, TContext>;
|
|
80
82
|
/** Which client capabilities to advertise to the agent. */
|
|
81
83
|
clientCapabilities?: AcpClientCapabilityConfig;
|
|
82
84
|
/** Optional Standard Schema; when set the assistant text is JSON-parsed and validated. */
|
|
@@ -59,6 +59,7 @@ export function boundedAcpSettings(node, bounds) {
|
|
|
59
59
|
readTextFile: capability('readTextFile'),
|
|
60
60
|
writeTextFile: capability('writeTextFile'),
|
|
61
61
|
terminal: capability('terminal'),
|
|
62
|
+
elicitation: capability('elicitation'),
|
|
62
63
|
},
|
|
63
64
|
session: reuse
|
|
64
65
|
? {
|
|
@@ -85,11 +86,15 @@ ${lines.join('\n')}`;
|
|
|
85
86
|
const NO_GRANT = {};
|
|
86
87
|
const DEFAULT_CAPABILITIES = {
|
|
87
88
|
readTextFile: true,
|
|
89
|
+
// Asking a person is gated, never a privilege to opt into: a host with
|
|
90
|
+
// nobody to answer withdraws it in its grant.
|
|
91
|
+
elicitation: true,
|
|
88
92
|
};
|
|
89
93
|
const CAPABILITIES = [
|
|
90
94
|
'readTextFile',
|
|
91
95
|
'writeTextFile',
|
|
92
96
|
'terminal',
|
|
97
|
+
'elicitation',
|
|
93
98
|
];
|
|
94
99
|
const KEEP_ALIVE_ORDER = {
|
|
95
100
|
step: 0,
|
|
@@ -37,7 +37,8 @@ function gateHooks(harness) {
|
|
|
37
37
|
return harness.beforeToolCall(layers, request.toolName, request.args, request.ctx, request.callId);
|
|
38
38
|
},
|
|
39
39
|
// A long operation asked a question (MCP Tasks `input_required`). It is held for
|
|
40
|
-
// a person
|
|
40
|
+
// a person as a question: the answer goes back to the operation; declined, the
|
|
41
|
+
// operation is left without one.
|
|
41
42
|
async answerInput(request) {
|
|
42
43
|
const question = request.status.request;
|
|
43
44
|
if (!request.ctx || !question) {
|
|
@@ -55,8 +56,16 @@ function gateHooks(harness) {
|
|
|
55
56
|
name: request.toolName,
|
|
56
57
|
args,
|
|
57
58
|
argsHash: heldArgsHash(request.toolName, args),
|
|
58
|
-
reason: '
|
|
59
|
+
reason: 'question',
|
|
59
60
|
request: question,
|
|
61
|
+
question: {
|
|
62
|
+
message: question.message,
|
|
63
|
+
...(question.schema
|
|
64
|
+
? {
|
|
65
|
+
schema: question.schema,
|
|
66
|
+
}
|
|
67
|
+
: {}),
|
|
68
|
+
},
|
|
60
69
|
},
|
|
61
70
|
});
|
|
62
71
|
return answer.resolution?.hasOutput
|
package/dist/index.d.ts
CHANGED
|
@@ -181,7 +181,7 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
|
|
|
181
181
|
/** @public */
|
|
182
182
|
export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, TurnCut, TurnCutReason, } from '@noetic-tools/types';
|
|
183
183
|
/** @public */
|
|
184
|
-
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldCallContext, HeldCallEvent, HeldCallHandler, HeldCallSettled, HeldResolution, HeldSteerPolicy, ItemSchemaConfig, KeptSteers, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, StoredThread, StoredTurn, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
|
|
184
|
+
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldCallContext, HeldCallEvent, HeldCallHandler, HeldCallSettled, HeldQuestion, HeldResolution, HeldSteerPolicy, ItemSchemaConfig, KeptSteers, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, StoredThread, StoredTurn, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
|
|
185
185
|
/** @public */
|
|
186
186
|
export type { ForgetOptions, ForgetReport, ListStoredOptions, PendingSpend, ReconcileSpendOptions, SpendSettlement, StoredExecution, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
187
187
|
/** @public */
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An agent's questions (`elicitation/create`) as held questions (spec 27
|
|
3
|
+
* § Questions the agent asks, spec 08 § Held tool calls): the host sees the same
|
|
4
|
+
* `tool_call_held` / `onHeld` / `pending()` question it sees for any other asker,
|
|
5
|
+
* and never learns the step is an agent.
|
|
6
|
+
*/
|
|
7
|
+
import type { AcpBoundElicitationHandler, Context, ContextData } from '@noetic-tools/types';
|
|
8
|
+
/** Everything a question's hold is filed and shown under. */
|
|
9
|
+
export interface QuestionAskerOptions {
|
|
10
|
+
ctx: Context<ContextData>;
|
|
11
|
+
agentId: string;
|
|
12
|
+
stepId: string;
|
|
13
|
+
}
|
|
14
|
+
/** Asks an agent's questions as held questions; see {@link questionAsker}. */
|
|
15
|
+
export interface QuestionAsker {
|
|
16
|
+
readonly ask: AcpBoundElicitationHandler;
|
|
17
|
+
/** Drop every question this step asked, answered or not: the step is over. */
|
|
18
|
+
release(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Answer an agent's questions by holding each for a person. A question's id is
|
|
22
|
+
* the step's dispatch path and a hash of the request with the agent's own
|
|
23
|
+
* JSON-RPC id for it — which a keeper keeps when it asks a reattached host
|
|
24
|
+
* again — so a resumed host asked the same question finds it, answered or
|
|
25
|
+
* not, and never asks the person twice. Without that id, the ordinal among
|
|
26
|
+
* identical requests stands in. An answer is kept until the step ends, so one
|
|
27
|
+
* taken just before the host died is still there when the question comes back.
|
|
28
|
+
* The agent is waiting on the answer, so the turn stays live while it is held.
|
|
29
|
+
*/
|
|
30
|
+
export declare function questionAsker(opts: QuestionAskerOptions): QuestionAsker;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An agent's questions (`elicitation/create`) as held questions (spec 27
|
|
3
|
+
* § Questions the agent asks, spec 08 § Held tool calls): the host sees the same
|
|
4
|
+
* `tool_call_held` / `onHeld` / `pending()` question it sees for any other asker,
|
|
5
|
+
* and never learns the step is an agent.
|
|
6
|
+
*/
|
|
7
|
+
import { frameworkCast } from '@noetic-tools/types';
|
|
8
|
+
import { ContextImpl } from '../runtime/context-impl.js';
|
|
9
|
+
import { heldArgsHash, heldCallsOf, heldScopeOf, holdAndWait, mayWriteHolds, } from '../runtime/held-calls.js';
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region Helpers
|
|
12
|
+
function isRecord(value) {
|
|
13
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The question a person sees: the message, and the form or the page. An ACP form
|
|
17
|
+
* is closed — the agent takes only the fields it described — so an answer with
|
|
18
|
+
* any other field is refused before the question settles.
|
|
19
|
+
*/
|
|
20
|
+
function questionOf(request) {
|
|
21
|
+
const schema = Reflect.get(request, 'requestedSchema');
|
|
22
|
+
const url = Reflect.get(request, 'url');
|
|
23
|
+
return {
|
|
24
|
+
message: request.message,
|
|
25
|
+
...(isRecord(schema)
|
|
26
|
+
? {
|
|
27
|
+
schema: {
|
|
28
|
+
...schema,
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
: {}),
|
|
33
|
+
...(typeof url === 'string'
|
|
34
|
+
? {
|
|
35
|
+
url,
|
|
36
|
+
}
|
|
37
|
+
: {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** What identifies one request across hosts: who asks, where, and what. */
|
|
41
|
+
function requestIdentity(request) {
|
|
42
|
+
return {
|
|
43
|
+
sessionId: Reflect.get(request, 'sessionId') ?? null,
|
|
44
|
+
toolCallId: Reflect.get(request, 'toolCallId') ?? null,
|
|
45
|
+
mode: request.mode,
|
|
46
|
+
question: questionOf(request),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** The step's dispatch path, or its id on a run with no ledger. */
|
|
50
|
+
function dispatchOf(ctx, stepId) {
|
|
51
|
+
return (ctx instanceof ContextImpl ? ctx.currentDispatch()?.path : undefined) ?? stepId;
|
|
52
|
+
}
|
|
53
|
+
/** An answer as the agent takes it: the form's fields, or none for a URL question. */
|
|
54
|
+
function acceptOf(output) {
|
|
55
|
+
if (!isRecord(output)) {
|
|
56
|
+
return {
|
|
57
|
+
action: 'accept',
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
// Checked against the question's schema when it was answered (held-question.ts).
|
|
61
|
+
return {
|
|
62
|
+
action: 'accept',
|
|
63
|
+
content: frameworkCast(output),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Answer an agent's questions by holding each for a person. A question's id is
|
|
68
|
+
* the step's dispatch path and a hash of the request with the agent's own
|
|
69
|
+
* JSON-RPC id for it — which a keeper keeps when it asks a reattached host
|
|
70
|
+
* again — so a resumed host asked the same question finds it, answered or
|
|
71
|
+
* not, and never asks the person twice. Without that id, the ordinal among
|
|
72
|
+
* identical requests stands in. An answer is kept until the step ends, so one
|
|
73
|
+
* taken just before the host died is still there when the question comes back.
|
|
74
|
+
* The agent is waiting on the answer, so the turn stays live while it is held.
|
|
75
|
+
*/
|
|
76
|
+
export function questionAsker(opts) {
|
|
77
|
+
const seen = new Map();
|
|
78
|
+
const asked = new Set();
|
|
79
|
+
/**
|
|
80
|
+
* Ids this host already asked under. An agent that asks again under the
|
|
81
|
+
* same id on the same host is asking a new question; a new host after a
|
|
82
|
+
* crash starts empty, so the keeper's re-ask finds the kept answer.
|
|
83
|
+
*/
|
|
84
|
+
const answeredHere = new Map();
|
|
85
|
+
const name = `${opts.agentId}:question`;
|
|
86
|
+
const harness = frameworkCast(opts.ctx.harness);
|
|
87
|
+
const idOf = (request, requestId) => {
|
|
88
|
+
const identity = heldArgsHash(name, {
|
|
89
|
+
...requestIdentity(request),
|
|
90
|
+
requestId: requestId ?? null,
|
|
91
|
+
});
|
|
92
|
+
if (requestId !== undefined) {
|
|
93
|
+
return `${dispatchOf(opts.ctx, opts.stepId)}:question:${identity}`;
|
|
94
|
+
}
|
|
95
|
+
const ordinal = seen.get(identity) ?? 0;
|
|
96
|
+
seen.set(identity, ordinal + 1);
|
|
97
|
+
return `${dispatchOf(opts.ctx, opts.stepId)}:question:${identity}#${ordinal}`;
|
|
98
|
+
};
|
|
99
|
+
return {
|
|
100
|
+
ask: async (request, info) => {
|
|
101
|
+
const base = idOf(request, info.requestId);
|
|
102
|
+
const again = answeredHere.get(base) ?? 0;
|
|
103
|
+
answeredHere.set(base, again + 1);
|
|
104
|
+
const callId = again === 0 ? base : `${base}~${again}`;
|
|
105
|
+
asked.add(callId);
|
|
106
|
+
const question = questionOf(request);
|
|
107
|
+
const args = {
|
|
108
|
+
message: question.message,
|
|
109
|
+
};
|
|
110
|
+
const answer = await holdAndWait({
|
|
111
|
+
harness,
|
|
112
|
+
ctx: opts.ctx,
|
|
113
|
+
park: false,
|
|
114
|
+
keepAnswer: true,
|
|
115
|
+
record: {
|
|
116
|
+
callId,
|
|
117
|
+
name,
|
|
118
|
+
args,
|
|
119
|
+
argsHash: heldArgsHash(name, args),
|
|
120
|
+
reason: 'question',
|
|
121
|
+
question,
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
return responseOf(answer.resolution);
|
|
125
|
+
},
|
|
126
|
+
release: async () => {
|
|
127
|
+
if (!mayWriteHolds(opts.ctx)) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const holds = heldCallsOf(harness);
|
|
131
|
+
const scope = heldScopeOf(opts.ctx);
|
|
132
|
+
for (const callId of asked) {
|
|
133
|
+
await holds.close(scope, callId);
|
|
134
|
+
}
|
|
135
|
+
asked.clear();
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** The agent's answer: accept with the form's fields, decline, or cancel. */
|
|
140
|
+
function responseOf(resolution) {
|
|
141
|
+
if (resolution?.hasOutput === true) {
|
|
142
|
+
return acceptOf(resolution.output);
|
|
143
|
+
}
|
|
144
|
+
if (resolution?.action === 'deny') {
|
|
145
|
+
return {
|
|
146
|
+
action: 'decline',
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
action: 'cancel',
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
@@ -16,6 +16,7 @@ declare const AcpSessionRecordSchema: z.ZodObject<{
|
|
|
16
16
|
sessionId: z.ZodString;
|
|
17
17
|
agentId: z.ZodString;
|
|
18
18
|
reattach: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
19
|
+
fingerprint: z.ZodOptional<z.ZodString>;
|
|
19
20
|
}, z.core.$strip>;
|
|
20
21
|
/** The agent session a step opened, as stored. */
|
|
21
22
|
export type AcpSessionRecord = z.infer<typeof AcpSessionRecordSchema>;
|
|
@@ -21,6 +21,11 @@ const AcpSessionRecordSchema = z.object({
|
|
|
21
21
|
agentId: z.string(),
|
|
22
22
|
/** How to reach the agent if it outlived the host that opened the session. */
|
|
23
23
|
reattach: z.record(z.string(), z.unknown()).optional(),
|
|
24
|
+
/**
|
|
25
|
+
* What the session was opened with (`AcpSession.fingerprint`). Absent on a
|
|
26
|
+
* record written before fingerprints were kept: such a session is accepted.
|
|
27
|
+
*/
|
|
28
|
+
fingerprint: z.string().optional(),
|
|
24
29
|
});
|
|
25
30
|
const BridgedOutputSchema = z.object({
|
|
26
31
|
output: z.string(),
|
|
@@ -6,13 +6,14 @@
|
|
|
6
6
|
* Core reaches the agent only through the `@noetic-tools/types` contract, so no
|
|
7
7
|
* protocol library or agent SDK enters its dependency graph.
|
|
8
8
|
*/
|
|
9
|
-
import { createMessage, extractAssistantText, frameworkCast, NoeticConfigError, NoeticErrorImpl, SteeringAction, } from '@noetic-tools/types';
|
|
9
|
+
import { createMessage, extractAssistantText, frameworkCast, isAcpCapabilityError, isAcpConnectError, NoeticConfigError, NoeticErrorImpl, SteeringAction, } from '@noetic-tools/types';
|
|
10
10
|
import { assertAgentTakesTools } from '../builders/acp-agent-checks.js';
|
|
11
11
|
import { runtimeOf } from '../connections/model-tools.js';
|
|
12
12
|
import { isRpcError, RpcFailure } from '../util/error-message.js';
|
|
13
13
|
import { AcpEventBridge } from './acp-events.js';
|
|
14
14
|
import { withHistoryPrompt } from './acp-history.js';
|
|
15
15
|
import { renderLayerContext } from './acp-layers.js';
|
|
16
|
+
import { questionAsker } from './acp-questions.js';
|
|
16
17
|
import { ACP_RESUME_NOTICE, acpSessionRecords } from './acp-resume.js';
|
|
17
18
|
import { AcpToolRunner, mergeBridgedItems, resolveAcpTools } from './acp-tools.js';
|
|
18
19
|
import { appendUserInput, MAX_STEERING_RETRIES, resolveLazy } from './execute-action.js';
|
|
@@ -200,6 +201,9 @@ function bindHostToStep(host, opts) {
|
|
|
200
201
|
stepId: opts.step.id,
|
|
201
202
|
})
|
|
202
203
|
: undefined;
|
|
204
|
+
// An agent's question is a question for a person: held like any other (spec 27
|
|
205
|
+
// § Questions the agent asks), answered by whoever answers held calls.
|
|
206
|
+
host.onElicitation = opts.questions.ask;
|
|
203
207
|
host.onSessionUpdate = opts.onUpdate;
|
|
204
208
|
host.onClientActivity = opts.onActivity;
|
|
205
209
|
// A step that gives no tools gets none, even on a session another step
|
|
@@ -251,6 +255,7 @@ function normalizedCapabilities(config) {
|
|
|
251
255
|
additionalDirectories: [
|
|
252
256
|
...(config?.additionalDirectories ?? []),
|
|
253
257
|
].sort(),
|
|
258
|
+
elicitation: config?.elicitation !== false,
|
|
254
259
|
});
|
|
255
260
|
}
|
|
256
261
|
/**
|
|
@@ -258,7 +263,7 @@ function normalizedCapabilities(config) {
|
|
|
258
263
|
* joining an existing one cannot change them either. Connection-scoped
|
|
259
264
|
* settings all fail the same way: a mismatch throws rather than being dropped.
|
|
260
265
|
*/
|
|
261
|
-
function assertSessionScopedSettingsMatch(step, live, cwd, tools) {
|
|
266
|
+
function assertSessionScopedSettingsMatch(step, live, cwd, tools, settings) {
|
|
262
267
|
const conflict = (setting, hint) => new NoeticConfigError({
|
|
263
268
|
code: 'ACP_SESSION_SETTING_CONFLICT',
|
|
264
269
|
message: `step.acpAgent(${JSON.stringify(step.id)}) reuses session '${step.session?.reuse}' but requests a different ${setting} than the session was created with.`,
|
|
@@ -267,6 +272,13 @@ function assertSessionScopedSettingsMatch(step, live, cwd, tools) {
|
|
|
267
272
|
if (cwd !== live.cwd) {
|
|
268
273
|
throw conflict('cwd', 'A session is created in one working directory. Give every step sharing a `session.reuse` key the same `cwd`, or use a separate session.');
|
|
269
274
|
}
|
|
275
|
+
// Instructions, the adapter's `_meta`, cwd and capabilities as the connection
|
|
276
|
+
// would send them, against what it sent when the session opened.
|
|
277
|
+
const opened = live.fingerprint;
|
|
278
|
+
if (opened !== undefined &&
|
|
279
|
+
opened !== live.connection.fingerprintFor(sessionRequest(cwd, settings))) {
|
|
280
|
+
throw conflict('instructions or agent settings', 'A session takes its instructions and its agent settings when it is created. Give every step sharing a `session.reuse` key the same `instructions` and agent, or use a separate session.');
|
|
281
|
+
}
|
|
270
282
|
// The agent reads its tool list once, so a step may serve any part of it —
|
|
271
283
|
// a call to a tool outside its part answers as unknown, as on `callModel` —
|
|
272
284
|
// but nothing the list lacks.
|
|
@@ -306,6 +318,35 @@ function assertCapabilitiesCompatible(step, live) {
|
|
|
306
318
|
hint: 'ACP negotiates client capabilities once per connection. Give every step sharing a `session.reuse` key the same `clientCapabilities`, or use a separate session.',
|
|
307
319
|
});
|
|
308
320
|
}
|
|
321
|
+
async function resolveSessionSettings(step, ctx) {
|
|
322
|
+
const instructions = await resolveLazy(step.instructions, ctx);
|
|
323
|
+
if (instructions === undefined || instructions.trim().length === 0) {
|
|
324
|
+
return {};
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
instructions,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
/** The session request for `cwd` and `settings`, as `fingerprintFor` takes it. */
|
|
331
|
+
function sessionRequest(cwd, settings) {
|
|
332
|
+
return {
|
|
333
|
+
cwd,
|
|
334
|
+
...settings,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/** JSON-RPC "resource not found", which an agent answers a load of a session it no longer has with. */
|
|
338
|
+
const RESOURCE_NOT_FOUND = -32002;
|
|
339
|
+
/**
|
|
340
|
+
* Whether a failed `session/load` says the agent no longer has the session —
|
|
341
|
+
* the one failure a resumed step starts over from. Anything else may mean the
|
|
342
|
+
* old turn is still there, so the step fails rather than repeat its work.
|
|
343
|
+
*/
|
|
344
|
+
function sessionIsGone(error) {
|
|
345
|
+
if (typeof error !== 'object' || error === null) {
|
|
346
|
+
return false;
|
|
347
|
+
}
|
|
348
|
+
return Reflect.get(error, 'code') === RESOURCE_NOT_FOUND;
|
|
349
|
+
}
|
|
309
350
|
/** Keeping a connection is always explicit; the default closes it with the step. */
|
|
310
351
|
function keepAliveOf(policy) {
|
|
311
352
|
return policy?.keepAlive ?? 'step';
|
|
@@ -332,12 +373,13 @@ function assertReuseIsKeptAlive(step) {
|
|
|
332
373
|
* session, gets a new one, and the step starts it over.
|
|
333
374
|
*/
|
|
334
375
|
async function sessionOn(connection, opts) {
|
|
335
|
-
const { cwd, loadId, resumeId } = opts;
|
|
376
|
+
const { cwd, loadId, resumeId, settings } = opts;
|
|
336
377
|
if (loadId) {
|
|
337
378
|
return {
|
|
338
379
|
session: await connection.loadSession({
|
|
339
380
|
sessionId: loadId,
|
|
340
381
|
cwd,
|
|
382
|
+
...settings,
|
|
341
383
|
}),
|
|
342
384
|
resumed: false,
|
|
343
385
|
};
|
|
@@ -347,8 +389,14 @@ async function sessionOn(connection, opts) {
|
|
|
347
389
|
.loadSession({
|
|
348
390
|
sessionId: resumeId,
|
|
349
391
|
cwd,
|
|
392
|
+
...settings,
|
|
350
393
|
})
|
|
351
|
-
.catch(() =>
|
|
394
|
+
.catch((error) => {
|
|
395
|
+
if (sessionIsGone(error)) {
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
throw error;
|
|
399
|
+
});
|
|
352
400
|
if (session) {
|
|
353
401
|
return {
|
|
354
402
|
session,
|
|
@@ -359,6 +407,7 @@ async function sessionOn(connection, opts) {
|
|
|
359
407
|
return {
|
|
360
408
|
session: await connection.newSession({
|
|
361
409
|
cwd,
|
|
410
|
+
...settings,
|
|
362
411
|
}),
|
|
363
412
|
resumed: false,
|
|
364
413
|
};
|
|
@@ -386,6 +435,9 @@ async function openSession(opts) {
|
|
|
386
435
|
const kept = await reattachTo(opts.agent, connectOptions, {
|
|
387
436
|
reattach: opts.reattach,
|
|
388
437
|
sessionId: opts.resumeId,
|
|
438
|
+
fingerprint: opts.fingerprint,
|
|
439
|
+
request: sessionRequest(opts.cwd, opts.settings),
|
|
440
|
+
stepId: opts.step.id,
|
|
389
441
|
});
|
|
390
442
|
if (kept) {
|
|
391
443
|
resumed = true;
|
|
@@ -398,6 +450,8 @@ async function openSession(opts) {
|
|
|
398
450
|
keepAlive,
|
|
399
451
|
cwd: opts.cwd,
|
|
400
452
|
tools: opts.tools?.tools,
|
|
453
|
+
// Checked equal to this step's when it reattached.
|
|
454
|
+
fingerprint: opts.fingerprint,
|
|
401
455
|
};
|
|
402
456
|
}
|
|
403
457
|
const connection = holdingConnections(await opts.agent.connect(connectOptions), opts.baseCtx, keepAlive);
|
|
@@ -410,6 +464,7 @@ async function openSession(opts) {
|
|
|
410
464
|
cwd: opts.cwd,
|
|
411
465
|
loadId: opts.step.session?.load,
|
|
412
466
|
resumeId: opts.resumeId,
|
|
467
|
+
settings: opts.settings,
|
|
413
468
|
});
|
|
414
469
|
resumed = opened.resumed;
|
|
415
470
|
const { session } = opened;
|
|
@@ -421,6 +476,7 @@ async function openSession(opts) {
|
|
|
421
476
|
keepAlive,
|
|
422
477
|
cwd: opts.cwd,
|
|
423
478
|
tools: opts.tools?.tools,
|
|
479
|
+
fingerprint: session.fingerprint,
|
|
424
480
|
};
|
|
425
481
|
}
|
|
426
482
|
catch (e) {
|
|
@@ -429,7 +485,7 @@ async function openSession(opts) {
|
|
|
429
485
|
}
|
|
430
486
|
});
|
|
431
487
|
if (!fresh) {
|
|
432
|
-
assertSessionScopedSettingsMatch(opts.step, live, opts.cwd, opts.tools);
|
|
488
|
+
assertSessionScopedSettingsMatch(opts.step, live, opts.cwd, opts.tools, opts.settings);
|
|
433
489
|
if (live.agentId !== opts.agent.agentId) {
|
|
434
490
|
throw new NoeticConfigError({
|
|
435
491
|
code: 'ACP_SESSION_AGENT_CONFLICT',
|
|
@@ -459,28 +515,70 @@ function whenHostExitsOf(ctx) {
|
|
|
459
515
|
* outlived its host, or undefined when there is none to reach — the agent is
|
|
460
516
|
* gone, or no longer has the session — so the step reloads or starts over.
|
|
461
517
|
*/
|
|
462
|
-
async function reattachTo(agent, connectOptions,
|
|
463
|
-
if (!reattach || sessionId === undefined) {
|
|
518
|
+
async function reattachTo(agent, connectOptions, opts) {
|
|
519
|
+
if (!opts.reattach || opts.sessionId === undefined) {
|
|
464
520
|
return undefined;
|
|
465
521
|
}
|
|
522
|
+
// Only "the agent is gone" starts the step over; any other failure fails it.
|
|
466
523
|
const connection = await agent
|
|
467
524
|
.connect({
|
|
468
525
|
...connectOptions,
|
|
469
|
-
reattach,
|
|
526
|
+
reattach: opts.reattach,
|
|
470
527
|
})
|
|
471
|
-
.catch(
|
|
528
|
+
.catch(goneOrThrow);
|
|
472
529
|
if (!connection) {
|
|
473
530
|
return undefined;
|
|
474
531
|
}
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
532
|
+
try {
|
|
533
|
+
const session = await connection.attachSession?.(opts.sessionId).catch(goneOrThrow);
|
|
534
|
+
if (!session?.resumeTurn) {
|
|
535
|
+
await connection.close().catch(() => undefined);
|
|
536
|
+
return undefined;
|
|
537
|
+
}
|
|
538
|
+
assertSameSettings(opts, connection);
|
|
539
|
+
return {
|
|
540
|
+
connection,
|
|
541
|
+
session,
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
catch (error) {
|
|
545
|
+
// The old turn may still be working: let go of it, never stop it, so a
|
|
546
|
+
// host that resumes with the settings it started with can still take it.
|
|
547
|
+
await letGo(connection);
|
|
548
|
+
throw error;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
/** Release this host's side of a reattached connection, leaving the agent running. */
|
|
552
|
+
async function letGo(connection) {
|
|
553
|
+
const release = connection.detach ?? connection.close;
|
|
554
|
+
await release.call(connection).catch(() => undefined);
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Undefined when the agent or its session is confirmed gone, the error itself
|
|
558
|
+
* otherwise: a connect failure that says nothing about the agent must not
|
|
559
|
+
* start its work over.
|
|
560
|
+
*/
|
|
561
|
+
function goneOrThrow(error) {
|
|
562
|
+
if (isAcpConnectError(error) && error.gone) {
|
|
478
563
|
return undefined;
|
|
479
564
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* A reattached session runs with what it was opened with. A step that would
|
|
569
|
+
* open it differently must not adopt it: the old turn may already have acted on
|
|
570
|
+
* the old instructions.
|
|
571
|
+
*/
|
|
572
|
+
function assertSameSettings(opts, connection) {
|
|
573
|
+
if (opts.fingerprint === undefined ||
|
|
574
|
+
opts.fingerprint === connection.fingerprintFor(opts.request)) {
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
throw new NoeticConfigError({
|
|
578
|
+
code: 'ACP_SESSION_SETTING_CONFLICT',
|
|
579
|
+
message: `step.acpAgent(${JSON.stringify(opts.stepId)}) resumes a session that was opened with different instructions or agent settings than the step now gives.`,
|
|
580
|
+
hint: 'A resumed step must resolve the same instructions, cwd and agent settings as the run that started it.',
|
|
581
|
+
});
|
|
484
582
|
}
|
|
485
583
|
/**
|
|
486
584
|
* A connection kept past its step holds the turn's connections until it
|
|
@@ -552,11 +650,23 @@ async function applySessionSelection(step, ctx, resolution, baseCtx) {
|
|
|
552
650
|
throw e;
|
|
553
651
|
}
|
|
554
652
|
}
|
|
555
|
-
/**
|
|
556
|
-
|
|
557
|
-
|
|
653
|
+
/**
|
|
654
|
+
* Whatever went wrong, as a Noetic error (spec 27 § Failures are Noetic errors):
|
|
655
|
+
* a host never sees a protocol error. A missing capability is the workflow's
|
|
656
|
+
* configuration; everything else the agent did, or failed to do, is the step
|
|
657
|
+
* failing, with the agent's own message.
|
|
658
|
+
*/
|
|
659
|
+
function stepFailure(step, cause, baseCtx) {
|
|
660
|
+
if (cause instanceof NoeticErrorImpl || cause instanceof NoeticConfigError) {
|
|
558
661
|
return cause;
|
|
559
662
|
}
|
|
663
|
+
if (isAcpCapabilityError(cause)) {
|
|
664
|
+
return new NoeticConfigError({
|
|
665
|
+
code: 'AGENT_CAPABILITY_MISSING',
|
|
666
|
+
message: `step.acpAgent(${JSON.stringify(step.id)}): ${cause.message}`,
|
|
667
|
+
hint: `The agent does not support '${cause.capability}'. Leave that setting off this step, or use an agent that supports it.`,
|
|
668
|
+
});
|
|
669
|
+
}
|
|
560
670
|
if (baseCtx.aborted) {
|
|
561
671
|
return new NoeticErrorImpl({
|
|
562
672
|
kind: 'cancelled',
|
|
@@ -573,18 +683,6 @@ function turnFailure(step, cause, baseCtx) {
|
|
|
573
683
|
retriesExhausted: false,
|
|
574
684
|
});
|
|
575
685
|
}
|
|
576
|
-
/**
|
|
577
|
-
* A failure while opening the session or applying its mode/model. Typed
|
|
578
|
-
* errors (capability, connect, config) pass through; a JSON-RPC rejection from
|
|
579
|
-
* the agent — or anything thrown that is not an Error — becomes the step's
|
|
580
|
-
* `step_failed` error with a readable message.
|
|
581
|
-
*/
|
|
582
|
-
function setupFailure(step, cause, baseCtx) {
|
|
583
|
-
if (cause instanceof Error && !isRpcError(cause)) {
|
|
584
|
-
return cause;
|
|
585
|
-
}
|
|
586
|
-
return turnFailure(step, cause, baseCtx);
|
|
587
|
-
}
|
|
588
686
|
/**
|
|
589
687
|
* The tools the agent is served. No `tools` offers every tool the run has,
|
|
590
688
|
* as on `callModel`, and an agent that cannot take tools then simply gets
|
|
@@ -638,15 +736,18 @@ async function runTurn(params) {
|
|
|
638
736
|
// Close the turn on the event surface before rethrowing. A consumer driving
|
|
639
737
|
// a UI off `getFullStream()` saw `response.created` and would otherwise
|
|
640
738
|
// wait forever for a completion that never comes — the stream just stops.
|
|
641
|
-
|
|
739
|
+
// The stream carries the same Noetic error `execute()` throws.
|
|
740
|
+
const failure = stepFailure(step, turnError.error ?? e, baseCtx);
|
|
741
|
+
bridge.abort(failure);
|
|
642
742
|
await discardIfFresh(resolution, baseCtx);
|
|
643
|
-
throw
|
|
743
|
+
throw failure;
|
|
644
744
|
}
|
|
645
745
|
await settle(tools);
|
|
646
746
|
if (turnError.error !== undefined) {
|
|
647
|
-
|
|
747
|
+
const failure = stepFailure(step, turnError.error, baseCtx);
|
|
748
|
+
bridge.abort(failure);
|
|
648
749
|
await discardIfFresh(resolution, baseCtx);
|
|
649
|
-
throw
|
|
750
|
+
throw failure;
|
|
650
751
|
}
|
|
651
752
|
if (tools) {
|
|
652
753
|
const merged = mergeBridgedItems(result.items, tools.takeFinished());
|
|
@@ -684,6 +785,31 @@ export async function executeAcpAgent(step, input, ctx, layers) {
|
|
|
684
785
|
const baseCtx = frameworkCast(ctx);
|
|
685
786
|
assertReuseIsKeptAlive(step);
|
|
686
787
|
const agent = await resolveAgent(step, ctx);
|
|
788
|
+
const questions = questionAsker({
|
|
789
|
+
ctx: baseCtx,
|
|
790
|
+
agentId: agent.agentId,
|
|
791
|
+
stepId: step.id,
|
|
792
|
+
});
|
|
793
|
+
// A question's answer is kept until the step ends, so a host that died after
|
|
794
|
+
// taking it and before the agent got it is not asked again (spec 27
|
|
795
|
+
// § Questions the agent asks). A step cut off with its host never gets here.
|
|
796
|
+
try {
|
|
797
|
+
return await runAcpStep({
|
|
798
|
+
step,
|
|
799
|
+
input,
|
|
800
|
+
ctx,
|
|
801
|
+
layers,
|
|
802
|
+
agent,
|
|
803
|
+
questions,
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
finally {
|
|
807
|
+
await questions.release().catch(() => undefined);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
async function runAcpStep(params) {
|
|
811
|
+
const { step, input, ctx, layers, agent, questions } = params;
|
|
812
|
+
const baseCtx = frameworkCast(ctx);
|
|
687
813
|
const resolvedPrompt = await resolveLazy(step.prompt, ctx);
|
|
688
814
|
const blocks = await resolveLazy(step.content, ctx);
|
|
689
815
|
const promptText = resolvedPrompt && resolvedPrompt.length > 0
|
|
@@ -699,6 +825,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
|
|
|
699
825
|
});
|
|
700
826
|
}
|
|
701
827
|
const cwd = (await resolveLazy(step.cwd, ctx)) ?? baseCtx.cwdState.cwd;
|
|
828
|
+
const settings = await resolveSessionSettings(step, ctx);
|
|
702
829
|
const tools = await resolveServedTools(step, ctx, layers, agent);
|
|
703
830
|
// Capture the conversation so far BEFORE appending this turn's prompt, so a
|
|
704
831
|
// fresh session can be seeded with it and the agent is not left guessing at
|
|
@@ -718,6 +845,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
|
|
|
718
845
|
const sameAgent = recorded?.agentId === agent.agentId;
|
|
719
846
|
const resumeId = sameAgent ? recorded?.sessionId : undefined;
|
|
720
847
|
const reattach = sameAgent ? recorded?.reattach : undefined;
|
|
848
|
+
const fingerprint = sameAgent ? recorded?.fingerprint : undefined;
|
|
721
849
|
// `session/load` replays the session's conversation as updates. They are the
|
|
722
850
|
// agent's history, not this turn's work: they reach raw-event consumers
|
|
723
851
|
// marked `replay: true`, and never the text, reasoning or item streams.
|
|
@@ -730,6 +858,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
|
|
|
730
858
|
const bindingFor = (events) => ({
|
|
731
859
|
step,
|
|
732
860
|
ctx: baseCtx,
|
|
861
|
+
questions,
|
|
733
862
|
agentId: agent.agentId,
|
|
734
863
|
layers,
|
|
735
864
|
onUpdate: (notification) => {
|
|
@@ -770,9 +899,11 @@ export async function executeAcpAgent(step, input, ctx, layers) {
|
|
|
770
899
|
tools,
|
|
771
900
|
resumeId,
|
|
772
901
|
reattach,
|
|
902
|
+
fingerprint,
|
|
903
|
+
settings,
|
|
773
904
|
})
|
|
774
905
|
.catch((cause) => {
|
|
775
|
-
throw
|
|
906
|
+
throw stepFailure(step, cause, baseCtx);
|
|
776
907
|
})
|
|
777
908
|
.finally(() => {
|
|
778
909
|
reloading = false;
|
|
@@ -780,16 +911,19 @@ export async function executeAcpAgent(step, input, ctx, layers) {
|
|
|
780
911
|
if (resolution.resumed) {
|
|
781
912
|
tools?.sessionReloaded();
|
|
782
913
|
}
|
|
783
|
-
|
|
914
|
+
// A reloaded session was opened again with this step's settings: its record
|
|
915
|
+
// takes the new fingerprint. A reattached one keeps the one it has.
|
|
916
|
+
if (resolution.fresh && !resolution.reattached) {
|
|
784
917
|
await sessions?.write({
|
|
785
918
|
sessionId: resolution.live.session.sessionId,
|
|
786
919
|
agentId: agent.agentId,
|
|
787
920
|
// How a resumed run reaches this agent if it outlives this host.
|
|
788
921
|
reattach: resolution.live.connection.reattach,
|
|
922
|
+
fingerprint: resolution.live.session.fingerprint,
|
|
789
923
|
});
|
|
790
924
|
}
|
|
791
925
|
await applySessionSelection(step, ctx, resolution, baseCtx).catch((cause) => {
|
|
792
|
-
throw
|
|
926
|
+
throw stepFailure(step, cause, baseCtx);
|
|
793
927
|
});
|
|
794
928
|
turnError.cancel = () => resolution.live.session.cancel();
|
|
795
929
|
// History seeds only a freshly opened session; a reused one already owns
|
|
@@ -22,6 +22,7 @@ declare const HeldRecordSchema: z.ZodObject<{
|
|
|
22
22
|
result: "result";
|
|
23
23
|
outcome: "outcome";
|
|
24
24
|
approval: "approval";
|
|
25
|
+
question: "question";
|
|
25
26
|
}>;
|
|
26
27
|
dueAt: z.ZodOptional<z.ZodNumber>;
|
|
27
28
|
onDue: z.ZodOptional<z.ZodEnum<{
|
|
@@ -29,6 +30,11 @@ declare const HeldRecordSchema: z.ZodObject<{
|
|
|
29
30
|
keep: "keep";
|
|
30
31
|
}>>;
|
|
31
32
|
request: z.ZodOptional<z.ZodUnknown>;
|
|
33
|
+
question: z.ZodOptional<z.ZodObject<{
|
|
34
|
+
message: z.ZodString;
|
|
35
|
+
schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
36
|
+
url: z.ZodOptional<z.ZodString>;
|
|
37
|
+
}, z.core.$strip>>;
|
|
32
38
|
resolution: z.ZodOptional<z.ZodObject<{
|
|
33
39
|
action: z.ZodOptional<z.ZodEnum<{
|
|
34
40
|
allow: "allow";
|
|
@@ -225,6 +231,14 @@ export declare function holdAndWait(opts: {
|
|
|
225
231
|
harness: HoldHost;
|
|
226
232
|
ctx: Context;
|
|
227
233
|
record: HeldRecord;
|
|
234
|
+
/** False when something outside the run waits on the answer: the turn stays live. Default true. */
|
|
235
|
+
park?: boolean;
|
|
236
|
+
/**
|
|
237
|
+
* Keep an answered record instead of dropping it, until the caller closes it:
|
|
238
|
+
* for an asker that may be asked the same question again after its answer
|
|
239
|
+
* was taken but before it reached whoever asked.
|
|
240
|
+
*/
|
|
241
|
+
keepAnswer?: boolean;
|
|
228
242
|
}): Promise<HeldAnswer>;
|
|
229
243
|
/**
|
|
230
244
|
* @internal
|
|
@@ -15,6 +15,7 @@ import { z } from 'zod';
|
|
|
15
15
|
import { emitFrameworkEvent, getBroadcaster } from './broadcaster-utils.js';
|
|
16
16
|
import { ContextImpl, rootIdOf } from './context-impl.js';
|
|
17
17
|
import { hashStepInput } from './durable/step-ledger.js';
|
|
18
|
+
import { questionAnswerProblem } from './held-question.js';
|
|
18
19
|
import { createInMemoryStorage } from './in-memory-storage.js';
|
|
19
20
|
//#region Types
|
|
20
21
|
const ResolutionSchema = z.object({
|
|
@@ -42,6 +43,7 @@ const HeldRecordSchema = z.object({
|
|
|
42
43
|
'approval',
|
|
43
44
|
'result',
|
|
44
45
|
'outcome',
|
|
46
|
+
'question',
|
|
45
47
|
]),
|
|
46
48
|
dueAt: z.number().optional(),
|
|
47
49
|
onDue: z
|
|
@@ -52,6 +54,14 @@ const HeldRecordSchema = z.object({
|
|
|
52
54
|
.optional(),
|
|
53
55
|
/** Passed back by a tool's `hold()`, for whoever answers. */
|
|
54
56
|
request: z.unknown().optional(),
|
|
57
|
+
/** The question, on a call held with `reason: 'question'`. */
|
|
58
|
+
question: z
|
|
59
|
+
.object({
|
|
60
|
+
message: z.string(),
|
|
61
|
+
schema: z.record(z.string(), z.unknown()).optional(),
|
|
62
|
+
url: z.string().optional(),
|
|
63
|
+
})
|
|
64
|
+
.optional(),
|
|
55
65
|
resolution: ResolutionSchema.optional(),
|
|
56
66
|
});
|
|
57
67
|
/**
|
|
@@ -94,6 +104,29 @@ function refused(callId, reason) {
|
|
|
94
104
|
reason,
|
|
95
105
|
});
|
|
96
106
|
}
|
|
107
|
+
/** Why `resolution` is the wrong kind of answer for `record`, or undefined. */
|
|
108
|
+
function wrongAnswerKind(record, resolution) {
|
|
109
|
+
// An unknown outcome takes either answer: "it landed, here is the result", or
|
|
110
|
+
// a decision on whether to run it again.
|
|
111
|
+
if (record.reason === 'outcome') {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
if (record.reason === 'question') {
|
|
115
|
+
if (resolution.hasOutput === true) {
|
|
116
|
+
const problem = questionAnswerProblem(record.question, resolution.output);
|
|
117
|
+
return problem ? `the answer does not fit the question: ${problem}` : undefined;
|
|
118
|
+
}
|
|
119
|
+
return resolution.action === 'deny'
|
|
120
|
+
? undefined
|
|
121
|
+
: 'a question takes an answer (output) or deny, not an approval';
|
|
122
|
+
}
|
|
123
|
+
if ((record.reason === 'result') === (resolution.hasOutput === true)) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
return record.reason === 'result'
|
|
127
|
+
? 'the call waits for a result, not an approval'
|
|
128
|
+
: 'the call waits for an approval, not a result';
|
|
129
|
+
}
|
|
97
130
|
function sameResolution(a, b) {
|
|
98
131
|
return JSON.stringify(a) === JSON.stringify(b);
|
|
99
132
|
}
|
|
@@ -168,6 +201,11 @@ export function toHeldCall(record) {
|
|
|
168
201
|
: {
|
|
169
202
|
request: record.request,
|
|
170
203
|
}),
|
|
204
|
+
...(record.question === undefined
|
|
205
|
+
? {}
|
|
206
|
+
: {
|
|
207
|
+
question: record.question,
|
|
208
|
+
}),
|
|
171
209
|
};
|
|
172
210
|
}
|
|
173
211
|
//#endregion
|
|
@@ -410,14 +448,9 @@ export class HeldCalls {
|
|
|
410
448
|
throw refused(callId, 'the answer is for a call with different arguments');
|
|
411
449
|
}
|
|
412
450
|
const resolution = toResolutionRecord(answer.resolution);
|
|
413
|
-
|
|
414
|
-
// a decision on whether to run it again.
|
|
415
|
-
const wrongKind = record.reason !== 'outcome' &&
|
|
416
|
-
(record.reason === 'result') !== (resolution.hasOutput === true);
|
|
451
|
+
const wrongKind = wrongAnswerKind(record, resolution);
|
|
417
452
|
if (wrongKind) {
|
|
418
|
-
throw refused(callId,
|
|
419
|
-
? 'the call waits for a result, not an approval'
|
|
420
|
-
: 'the call waits for an approval, not a result');
|
|
453
|
+
throw refused(callId, wrongKind);
|
|
421
454
|
}
|
|
422
455
|
if (record.resolution) {
|
|
423
456
|
if (sameResolution(record.resolution, resolution)) {
|
|
@@ -610,6 +643,11 @@ export async function holdAndWait(opts) {
|
|
|
610
643
|
for (;;) {
|
|
611
644
|
const current = await holds.load(executionId, callId);
|
|
612
645
|
const settled = current?.resolution !== undefined;
|
|
646
|
+
if (settled && opts.keepAnswer) {
|
|
647
|
+
return {
|
|
648
|
+
resolution: current?.resolution,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
613
651
|
if (!current || settled || isOverdue(current, holds.now())) {
|
|
614
652
|
if (mayWriteHolds(opts.ctx)) {
|
|
615
653
|
await holds.close(executionId, callId);
|
|
@@ -624,6 +662,7 @@ export async function holdAndWait(opts) {
|
|
|
624
662
|
callIds: [
|
|
625
663
|
callId,
|
|
626
664
|
],
|
|
665
|
+
park: opts.park,
|
|
627
666
|
});
|
|
628
667
|
}
|
|
629
668
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A question held for a person (spec 08 § Held tool calls, `reason: 'question'`):
|
|
3
|
+
* checking that an answer fits the question's form before the question settles.
|
|
4
|
+
*
|
|
5
|
+
* A question's `schema` is the flat form both askers use — MCP Tasks
|
|
6
|
+
* `input_required` and ACP `elicitation/create`: an object whose own properties
|
|
7
|
+
* are strings, numbers, integers, booleans or arrays of strings, with the usual
|
|
8
|
+
* constraints (`enum`, `minLength`/`maxLength`, `pattern`, `minimum`/`maximum`,
|
|
9
|
+
* `minItems`/`maxItems`, `items.enum`), some of them `required`, and
|
|
10
|
+
* `additionalProperties: false` to refuse any other field.
|
|
11
|
+
*/
|
|
12
|
+
import type { HeldQuestion } from '@noetic-tools/types';
|
|
13
|
+
/**
|
|
14
|
+
* Why `answer` does not fit `question`'s form, or undefined when it does (or the
|
|
15
|
+
* question has no form). Only the answer's own fields count.
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
export declare function questionAnswerProblem(question: HeldQuestion | undefined, answer: unknown): string | undefined;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A question held for a person (spec 08 § Held tool calls, `reason: 'question'`):
|
|
3
|
+
* checking that an answer fits the question's form before the question settles.
|
|
4
|
+
*
|
|
5
|
+
* A question's `schema` is the flat form both askers use — MCP Tasks
|
|
6
|
+
* `input_required` and ACP `elicitation/create`: an object whose own properties
|
|
7
|
+
* are strings, numbers, integers, booleans or arrays of strings, with the usual
|
|
8
|
+
* constraints (`enum`, `minLength`/`maxLength`, `pattern`, `minimum`/`maximum`,
|
|
9
|
+
* `minItems`/`maxItems`, `items.enum`), some of them `required`, and
|
|
10
|
+
* `additionalProperties: false` to refuse any other field.
|
|
11
|
+
*/
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region Helpers
|
|
14
|
+
function isRecord(value) {
|
|
15
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
function numberAt(schema, key) {
|
|
18
|
+
const value = schema[key];
|
|
19
|
+
return typeof value === 'number' ? value : undefined;
|
|
20
|
+
}
|
|
21
|
+
/** The values a titled single-select (`oneOf: [{ const, title }]`) allows. */
|
|
22
|
+
function titledChoices(schema) {
|
|
23
|
+
const choices = schema.oneOf ?? schema.anyOf;
|
|
24
|
+
if (!Array.isArray(choices)) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
return choices.filter(isRecord).map((choice) => choice.const);
|
|
28
|
+
}
|
|
29
|
+
function checkString(name, schema, value) {
|
|
30
|
+
if (typeof value !== 'string') {
|
|
31
|
+
return `'${name}' must be a string`;
|
|
32
|
+
}
|
|
33
|
+
// JSON Schema counts characters as code points, not UTF-16 units.
|
|
34
|
+
const length = [
|
|
35
|
+
...value,
|
|
36
|
+
].length;
|
|
37
|
+
const min = numberAt(schema, 'minLength');
|
|
38
|
+
if (min !== undefined && length < min) {
|
|
39
|
+
return `'${name}' must be at least ${min} characters`;
|
|
40
|
+
}
|
|
41
|
+
const max = numberAt(schema, 'maxLength');
|
|
42
|
+
if (max !== undefined && length > max) {
|
|
43
|
+
return `'${name}' must be at most ${max} characters`;
|
|
44
|
+
}
|
|
45
|
+
const pattern = schema.pattern;
|
|
46
|
+
if (typeof pattern === 'string' && !new RegExp(pattern, 'u').test(value)) {
|
|
47
|
+
return `'${name}' must match ${pattern}`;
|
|
48
|
+
}
|
|
49
|
+
const choices = titledChoices(schema);
|
|
50
|
+
if (choices && !choices.includes(value)) {
|
|
51
|
+
return `'${name}' must be one of ${JSON.stringify(choices)}`;
|
|
52
|
+
}
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
function checkRange(name, schema, value) {
|
|
56
|
+
const min = numberAt(schema, 'minimum');
|
|
57
|
+
if (min !== undefined && value < min) {
|
|
58
|
+
return `'${name}' must be at least ${min}`;
|
|
59
|
+
}
|
|
60
|
+
const max = numberAt(schema, 'maximum');
|
|
61
|
+
if (max !== undefined && value > max) {
|
|
62
|
+
return `'${name}' must be at most ${max}`;
|
|
63
|
+
}
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
function checkNumber(name, schema, value) {
|
|
67
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
68
|
+
return `'${name}' must be a number`;
|
|
69
|
+
}
|
|
70
|
+
return checkRange(name, schema, value);
|
|
71
|
+
}
|
|
72
|
+
function checkInteger(name, schema, value) {
|
|
73
|
+
if (typeof value !== 'number' || !Number.isInteger(value)) {
|
|
74
|
+
return `'${name}' must be an integer`;
|
|
75
|
+
}
|
|
76
|
+
return checkRange(name, schema, value);
|
|
77
|
+
}
|
|
78
|
+
function checkBoolean(name, _schema, value) {
|
|
79
|
+
return typeof value === 'boolean' ? undefined : `'${name}' must be a boolean`;
|
|
80
|
+
}
|
|
81
|
+
/** The choices an array's items may take: `items.enum`, or `items.anyOf[].const`. */
|
|
82
|
+
function itemChoices(schema) {
|
|
83
|
+
const items = schema.items;
|
|
84
|
+
if (!isRecord(items)) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
if (Array.isArray(items.enum)) {
|
|
88
|
+
return items.enum;
|
|
89
|
+
}
|
|
90
|
+
if (!Array.isArray(items.anyOf)) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
return items.anyOf.filter(isRecord).map((choice) => choice.const);
|
|
94
|
+
}
|
|
95
|
+
function checkArray(name, schema, value) {
|
|
96
|
+
// `Array.from` fills holes with `undefined`, which `every` would skip.
|
|
97
|
+
if (!Array.isArray(value) || !Array.from(value).every((item) => typeof item === 'string')) {
|
|
98
|
+
return `'${name}' must be a list of strings`;
|
|
99
|
+
}
|
|
100
|
+
const min = numberAt(schema, 'minItems');
|
|
101
|
+
if (min !== undefined && value.length < min) {
|
|
102
|
+
return `'${name}' must have at least ${min} items`;
|
|
103
|
+
}
|
|
104
|
+
const max = numberAt(schema, 'maxItems');
|
|
105
|
+
if (max !== undefined && value.length > max) {
|
|
106
|
+
return `'${name}' must have at most ${max} items`;
|
|
107
|
+
}
|
|
108
|
+
const choices = itemChoices(schema);
|
|
109
|
+
if (choices && !value.every((item) => choices.includes(item))) {
|
|
110
|
+
return `'${name}' items must be among ${JSON.stringify(choices)}`;
|
|
111
|
+
}
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
const TYPE_CHECKS = {
|
|
115
|
+
string: checkString,
|
|
116
|
+
number: checkNumber,
|
|
117
|
+
integer: checkInteger,
|
|
118
|
+
boolean: checkBoolean,
|
|
119
|
+
array: checkArray,
|
|
120
|
+
};
|
|
121
|
+
/** Why `value` does not fit the property `name`'s schema, or undefined when it does. */
|
|
122
|
+
function propertyProblem(name, schema, value) {
|
|
123
|
+
if (!isRecord(schema)) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
const type = schema.type;
|
|
127
|
+
const check = typeof type === 'string' ? TYPE_CHECKS[type] : undefined;
|
|
128
|
+
const problem = check?.(name, schema, value);
|
|
129
|
+
if (problem) {
|
|
130
|
+
return problem;
|
|
131
|
+
}
|
|
132
|
+
const choices = schema.enum;
|
|
133
|
+
if (Array.isArray(choices) && !choices.includes(value)) {
|
|
134
|
+
return `'${name}' must be one of ${JSON.stringify(choices)}`;
|
|
135
|
+
}
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
function requiredOf(schema) {
|
|
139
|
+
const required = schema.required;
|
|
140
|
+
if (!Array.isArray(required)) {
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
return required.filter((name) => typeof name === 'string');
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region Public API
|
|
147
|
+
/**
|
|
148
|
+
* Why `answer` does not fit `question`'s form, or undefined when it does (or the
|
|
149
|
+
* question has no form). Only the answer's own fields count.
|
|
150
|
+
* @internal
|
|
151
|
+
*/
|
|
152
|
+
export function questionAnswerProblem(question, answer) {
|
|
153
|
+
const schema = question?.schema;
|
|
154
|
+
if (!schema) {
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
if (!isRecord(answer)) {
|
|
158
|
+
return 'the answer must be an object of the form’s fields';
|
|
159
|
+
}
|
|
160
|
+
for (const name of requiredOf(schema)) {
|
|
161
|
+
if (!Object.hasOwn(answer, name) || answer[name] === undefined) {
|
|
162
|
+
return `'${name}' is required`;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
166
|
+
const closed = schema.additionalProperties === false;
|
|
167
|
+
for (const [name, value] of Object.entries(answer)) {
|
|
168
|
+
const described = Object.hasOwn(properties, name);
|
|
169
|
+
if (!described && closed) {
|
|
170
|
+
return `'${name}' is not a field of the form`;
|
|
171
|
+
}
|
|
172
|
+
const problem = described ? propertyProblem(name, properties[name], value) : undefined;
|
|
173
|
+
if (problem) {
|
|
174
|
+
return problem;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noetic-tools/core",
|
|
3
|
-
"version": "5.22.0-next.
|
|
3
|
+
"version": "5.22.0-next.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"@noetic-tools/context": "^2.0.0-next.1",
|
|
72
|
-
"@noetic-tools/types": "^3.19.0-next.
|
|
72
|
+
"@noetic-tools/types": "^3.19.0-next.6",
|
|
73
73
|
"@openrouter/agent": "^0.11.0",
|
|
74
74
|
"@openrouter/sdk": "1.4.25",
|
|
75
75
|
"jsonata": "2.2.2",
|
|
@@ -2879,6 +2879,10 @@
|
|
|
2879
2879
|
"type": "string",
|
|
2880
2880
|
"minLength": 1
|
|
2881
2881
|
},
|
|
2882
|
+
"instructions": {
|
|
2883
|
+
"type": "string",
|
|
2884
|
+
"minLength": 1
|
|
2885
|
+
},
|
|
2882
2886
|
"cwd": {
|
|
2883
2887
|
"type": "string",
|
|
2884
2888
|
"minLength": 1
|
|
@@ -3153,6 +3157,9 @@
|
|
|
3153
3157
|
},
|
|
3154
3158
|
"terminal": {
|
|
3155
3159
|
"type": "boolean"
|
|
3160
|
+
},
|
|
3161
|
+
"elicitation": {
|
|
3162
|
+
"type": "boolean"
|
|
3156
3163
|
}
|
|
3157
3164
|
},
|
|
3158
3165
|
"additionalProperties": false
|