@lushly-dev/afd-server 2.5.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +100 -21
  2. package/dist/admission.d.ts +137 -0
  3. package/dist/admission.d.ts.map +1 -0
  4. package/dist/admission.js +144 -0
  5. package/dist/admission.js.map +1 -0
  6. package/dist/app-call-registry.d.ts +2 -2
  7. package/dist/app-call-registry.d.ts.map +1 -1
  8. package/dist/app-call-registry.js +12 -4
  9. package/dist/app-call-registry.js.map +1 -1
  10. package/dist/approval-admission.d.ts +47 -1
  11. package/dist/approval-admission.d.ts.map +1 -1
  12. package/dist/approval-admission.js +87 -0
  13. package/dist/approval-admission.js.map +1 -1
  14. package/dist/approval-crypto.d.ts +16 -2
  15. package/dist/approval-crypto.d.ts.map +1 -1
  16. package/dist/approval-crypto.js +45 -11
  17. package/dist/approval-crypto.js.map +1 -1
  18. package/dist/approval-process-state.d.ts +3 -0
  19. package/dist/approval-process-state.d.ts.map +1 -1
  20. package/dist/approval-process-state.js +2 -0
  21. package/dist/approval-process-state.js.map +1 -1
  22. package/dist/approval-relay.d.ts +41 -5
  23. package/dist/approval-relay.d.ts.map +1 -1
  24. package/dist/approval-relay.js +8 -11
  25. package/dist/approval-relay.js.map +1 -1
  26. package/dist/approval-up-front.d.ts.map +1 -1
  27. package/dist/approval-up-front.js +62 -13
  28. package/dist/approval-up-front.js.map +1 -1
  29. package/dist/approval.d.ts +55 -3
  30. package/dist/approval.d.ts.map +1 -1
  31. package/dist/approval.js +208 -54
  32. package/dist/approval.js.map +1 -1
  33. package/dist/approver.d.ts +2 -2
  34. package/dist/approver.d.ts.map +1 -1
  35. package/dist/approver.js +6 -6
  36. package/dist/approver.js.map +1 -1
  37. package/dist/auth-middleware-check.d.ts +23 -0
  38. package/dist/auth-middleware-check.d.ts.map +1 -0
  39. package/dist/auth-middleware-check.js +48 -0
  40. package/dist/auth-middleware-check.js.map +1 -0
  41. package/dist/bootstrap/afd-context.d.ts.map +1 -1
  42. package/dist/bootstrap/afd-context.js +27 -3
  43. package/dist/bootstrap/afd-context.js.map +1 -1
  44. package/dist/bootstrap/afd-help.d.ts +3 -1
  45. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  46. package/dist/bootstrap/afd-help.js +2 -0
  47. package/dist/bootstrap/afd-help.js.map +1 -1
  48. package/dist/bootstrap/described-command.d.ts +2 -1
  49. package/dist/bootstrap/described-command.d.ts.map +1 -1
  50. package/dist/bootstrap/described-command.js.map +1 -1
  51. package/dist/command-allow.d.ts +4 -4
  52. package/dist/command-allow.d.ts.map +1 -1
  53. package/dist/command-allow.js +10 -15
  54. package/dist/command-allow.js.map +1 -1
  55. package/dist/command-routing.d.ts +56 -8
  56. package/dist/command-routing.d.ts.map +1 -1
  57. package/dist/command-routing.js +82 -16
  58. package/dist/command-routing.js.map +1 -1
  59. package/dist/command-timeout.d.ts.map +1 -1
  60. package/dist/command-timeout.js +8 -1
  61. package/dist/command-timeout.js.map +1 -1
  62. package/dist/confirmation-gate.d.ts +7 -7
  63. package/dist/confirmation-gate.d.ts.map +1 -1
  64. package/dist/confirmation-gate.js +44 -26
  65. package/dist/confirmation-gate.js.map +1 -1
  66. package/dist/confirmations.d.ts +46 -3
  67. package/dist/confirmations.d.ts.map +1 -1
  68. package/dist/confirmations.js +6 -7
  69. package/dist/confirmations.js.map +1 -1
  70. package/dist/context-fields.d.ts +16 -1
  71. package/dist/context-fields.d.ts.map +1 -1
  72. package/dist/context-fields.js +21 -4
  73. package/dist/context-fields.js.map +1 -1
  74. package/dist/context-scope.d.ts +3 -3
  75. package/dist/context-scope.d.ts.map +1 -1
  76. package/dist/context-scope.js +7 -8
  77. package/dist/context-scope.js.map +1 -1
  78. package/dist/define-core.d.ts +39 -3
  79. package/dist/define-core.d.ts.map +1 -1
  80. package/dist/define-core.js +20 -4
  81. package/dist/define-core.js.map +1 -1
  82. package/dist/define.d.ts +2 -2
  83. package/dist/define.d.ts.map +1 -1
  84. package/dist/define.js.map +1 -1
  85. package/dist/direct-registry.d.ts +30 -8
  86. package/dist/direct-registry.d.ts.map +1 -1
  87. package/dist/direct-registry.js +26 -5
  88. package/dist/direct-registry.js.map +1 -1
  89. package/dist/direct-tool-surface.d.ts +3 -1
  90. package/dist/direct-tool-surface.d.ts.map +1 -1
  91. package/dist/direct-tool-surface.js +22 -5
  92. package/dist/direct-tool-surface.js.map +1 -1
  93. package/dist/direct.d.ts +4 -2
  94. package/dist/direct.d.ts.map +1 -1
  95. package/dist/direct.js +2 -0
  96. package/dist/direct.js.map +1 -1
  97. package/dist/execution.d.ts +35 -6
  98. package/dist/execution.d.ts.map +1 -1
  99. package/dist/execution.js +108 -15
  100. package/dist/execution.js.map +1 -1
  101. package/dist/frontmatter.js +16 -13
  102. package/dist/frontmatter.js.map +1 -1
  103. package/dist/host-state.d.ts +96 -0
  104. package/dist/host-state.d.ts.map +1 -0
  105. package/dist/host-state.js +62 -0
  106. package/dist/host-state.js.map +1 -0
  107. package/dist/http-handler.d.ts +31 -12
  108. package/dist/http-handler.d.ts.map +1 -1
  109. package/dist/http-handler.js +138 -102
  110. package/dist/http-handler.js.map +1 -1
  111. package/dist/http-security.js +2 -2
  112. package/dist/http-security.js.map +1 -1
  113. package/dist/http-sessions.d.ts +10 -0
  114. package/dist/http-sessions.d.ts.map +1 -1
  115. package/dist/http-sessions.js +12 -2
  116. package/dist/http-sessions.js.map +1 -1
  117. package/dist/http-sse.d.ts +9 -0
  118. package/dist/http-sse.d.ts.map +1 -1
  119. package/dist/http-sse.js +12 -3
  120. package/dist/http-sse.js.map +1 -1
  121. package/dist/human-relay.d.ts +195 -0
  122. package/dist/human-relay.d.ts.map +1 -0
  123. package/dist/human-relay.js +697 -0
  124. package/dist/human-relay.js.map +1 -0
  125. package/dist/idempotency-step.d.ts +243 -0
  126. package/dist/idempotency-step.d.ts.map +1 -0
  127. package/dist/idempotency-step.js +419 -0
  128. package/dist/idempotency-step.js.map +1 -0
  129. package/dist/idempotency-store.d.ts +107 -0
  130. package/dist/idempotency-store.d.ts.map +1 -0
  131. package/dist/idempotency-store.js +100 -0
  132. package/dist/idempotency-store.js.map +1 -0
  133. package/dist/index.d.ts +10 -7
  134. package/dist/index.d.ts.map +1 -1
  135. package/dist/index.js +9 -5
  136. package/dist/index.js.map +1 -1
  137. package/dist/instance-state.d.ts +7 -0
  138. package/dist/instance-state.d.ts.map +1 -1
  139. package/dist/instance-state.js +5 -2
  140. package/dist/instance-state.js.map +1 -1
  141. package/dist/journal-off-tape.d.ts +52 -0
  142. package/dist/journal-off-tape.d.ts.map +1 -0
  143. package/dist/journal-off-tape.js +150 -0
  144. package/dist/journal-off-tape.js.map +1 -0
  145. package/dist/journal-replay.d.ts.map +1 -1
  146. package/dist/journal-replay.js +7 -0
  147. package/dist/journal-replay.js.map +1 -1
  148. package/dist/journal-view.d.ts +50 -0
  149. package/dist/journal-view.d.ts.map +1 -0
  150. package/dist/journal-view.js +214 -0
  151. package/dist/journal-view.js.map +1 -0
  152. package/dist/journal.d.ts +24 -5
  153. package/dist/journal.d.ts.map +1 -1
  154. package/dist/journal.js +91 -40
  155. package/dist/journal.js.map +1 -1
  156. package/dist/lazy-tools.d.ts +13 -3
  157. package/dist/lazy-tools.d.ts.map +1 -1
  158. package/dist/lazy-tools.js +9 -2
  159. package/dist/lazy-tools.js.map +1 -1
  160. package/dist/mcp-auth-dispatch.d.ts +1 -1
  161. package/dist/mcp-auth-dispatch.d.ts.map +1 -1
  162. package/dist/mcp-auth-dispatch.js +2 -1
  163. package/dist/mcp-auth-dispatch.js.map +1 -1
  164. package/dist/mcp-auth-jwt.d.ts +11 -4
  165. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  166. package/dist/mcp-auth-jwt.js +11 -9
  167. package/dist/mcp-auth-jwt.js.map +1 -1
  168. package/dist/mcp-auth-resource.d.ts +27 -3
  169. package/dist/mcp-auth-resource.d.ts.map +1 -1
  170. package/dist/mcp-auth-resource.js +37 -10
  171. package/dist/mcp-auth-resource.js.map +1 -1
  172. package/dist/mcp-auth-rules.d.ts +97 -18
  173. package/dist/mcp-auth-rules.d.ts.map +1 -1
  174. package/dist/mcp-auth-rules.js +194 -37
  175. package/dist/mcp-auth-rules.js.map +1 -1
  176. package/dist/mcp-auth-view.d.ts +3 -3
  177. package/dist/mcp-auth-view.d.ts.map +1 -1
  178. package/dist/mcp-auth-view.js +62 -25
  179. package/dist/mcp-auth-view.js.map +1 -1
  180. package/dist/mcp-auth.d.ts +27 -4
  181. package/dist/mcp-auth.d.ts.map +1 -1
  182. package/dist/mcp-auth.js +55 -14
  183. package/dist/mcp-auth.js.map +1 -1
  184. package/dist/mcp-modern.d.ts +70 -7
  185. package/dist/mcp-modern.d.ts.map +1 -1
  186. package/dist/mcp-modern.js +225 -111
  187. package/dist/mcp-modern.js.map +1 -1
  188. package/dist/meta-argument.d.ts +2 -1
  189. package/dist/meta-argument.d.ts.map +1 -1
  190. package/dist/meta-argument.js +13 -2
  191. package/dist/meta-argument.js.map +1 -1
  192. package/dist/meta-tools.js +2 -2
  193. package/dist/meta-tools.js.map +1 -1
  194. package/dist/middleware.d.ts +18 -3
  195. package/dist/middleware.d.ts.map +1 -1
  196. package/dist/middleware.js +53 -7
  197. package/dist/middleware.js.map +1 -1
  198. package/dist/output-budget.d.ts.map +1 -1
  199. package/dist/output-budget.js +2 -0
  200. package/dist/output-budget.js.map +1 -1
  201. package/dist/principal-binding.js +1 -1
  202. package/dist/principal-binding.js.map +1 -1
  203. package/dist/relay-evidence.d.ts +74 -0
  204. package/dist/relay-evidence.d.ts.map +1 -0
  205. package/dist/relay-evidence.js +143 -0
  206. package/dist/relay-evidence.js.map +1 -0
  207. package/dist/request-context.d.ts +4 -0
  208. package/dist/request-context.d.ts.map +1 -1
  209. package/dist/request-context.js +12 -2
  210. package/dist/request-context.js.map +1 -1
  211. package/dist/resources.js +1 -1
  212. package/dist/resources.js.map +1 -1
  213. package/dist/schema.d.ts +4 -3
  214. package/dist/schema.d.ts.map +1 -1
  215. package/dist/schema.js +3 -3
  216. package/dist/schema.js.map +1 -1
  217. package/dist/scope-view.d.ts +18 -5
  218. package/dist/scope-view.d.ts.map +1 -1
  219. package/dist/scope-view.js +9 -8
  220. package/dist/scope-view.js.map +1 -1
  221. package/dist/server-types.d.ts +44 -16
  222. package/dist/server-types.d.ts.map +1 -1
  223. package/dist/server-types.js.map +1 -1
  224. package/dist/server.d.ts +26 -0
  225. package/dist/server.d.ts.map +1 -1
  226. package/dist/server.js +359 -89
  227. package/dist/server.js.map +1 -1
  228. package/dist/task-dispatch.d.ts +12 -6
  229. package/dist/task-dispatch.d.ts.map +1 -1
  230. package/dist/task-dispatch.js +11 -12
  231. package/dist/task-dispatch.js.map +1 -1
  232. package/dist/task-input.d.ts +29 -0
  233. package/dist/task-input.d.ts.map +1 -0
  234. package/dist/task-input.js +75 -0
  235. package/dist/task-input.js.map +1 -0
  236. package/dist/tasks-input-gate.d.ts +61 -0
  237. package/dist/tasks-input-gate.d.ts.map +1 -0
  238. package/dist/tasks-input-gate.js +325 -0
  239. package/dist/tasks-input-gate.js.map +1 -0
  240. package/dist/tasks-input-runner.d.ts +125 -0
  241. package/dist/tasks-input-runner.d.ts.map +1 -0
  242. package/dist/tasks-input-runner.js +1017 -0
  243. package/dist/tasks-input-runner.js.map +1 -0
  244. package/dist/tasks-runtime.d.ts +34 -7
  245. package/dist/tasks-runtime.d.ts.map +1 -1
  246. package/dist/tasks-runtime.js +545 -94
  247. package/dist/tasks-runtime.js.map +1 -1
  248. package/dist/tasks.d.ts +196 -25
  249. package/dist/tasks.d.ts.map +1 -1
  250. package/dist/tasks.js +188 -26
  251. package/dist/tasks.js.map +1 -1
  252. package/dist/tool-router.d.ts +62 -3
  253. package/dist/tool-router.d.ts.map +1 -1
  254. package/dist/tool-router.js +251 -101
  255. package/dist/tool-router.js.map +1 -1
  256. package/dist/tools.d.ts +32 -0
  257. package/dist/tools.d.ts.map +1 -1
  258. package/dist/tools.js +154 -40
  259. package/dist/tools.js.map +1 -1
  260. package/dist/up-front-steps.d.ts +8 -0
  261. package/dist/up-front-steps.d.ts.map +1 -1
  262. package/dist/up-front-steps.js +50 -1
  263. package/dist/up-front-steps.js.map +1 -1
  264. package/dist/validation.d.ts +14 -0
  265. package/dist/validation.d.ts.map +1 -1
  266. package/dist/validation.js +62 -17
  267. package/dist/validation.js.map +1 -1
  268. package/package.json +15 -11
@@ -0,0 +1,1017 @@
1
+ /**
2
+ * @fileoverview Task `input_required` gate driver (`spec/tasks.md`, "Asking a person in a task",
3
+ * pending `tasks` profile 1.1; #2507): host-verified relay pre-check and runner loop, confirmation
4
+ * elicitation loop, approval step runner, and atomic `handler-started` barrier.
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { ErrorCodes, failure } from '@lushly-dev/afd-core';
8
+ import { ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';
9
+ import { canonicalJson } from './approval.js';
10
+ import { APPROVAL_REQUESTED_SCHEMA, withoutApprovalRelay, } from './approval-relay.js';
11
+ import { CONFIRM_REQUESTED_SCHEMA } from './confirmations.js';
12
+ import { applyContextFields } from './context-fields.js';
13
+ import { allowsUrlElicitation, hostVerifiedUnrelayable, humanRelayChannel, } from './human-relay.js';
14
+ import { credentialsBinding } from './principal-binding.js';
15
+ import { attachRelayDispatchAdmission, attachRelayEvidence, attachRelayValidatedInput, } from './relay-evidence.js';
16
+ import { DEFAULT_TASK_FORM_TIMEOUT_MS, isTaskExpired, isTerminalTaskStatus, } from './tasks.js';
17
+ import { buildRelayPromptRequest, confirmDeclinedError, confirmUnansweredError, newQuestionKey, prepareRelayApproval, relayPendingListRefusal, relayUrlRequiredError, } from './tasks-input-gate.js';
18
+ const MAX_TIMEOUT_MS = 2_147_483_647;
19
+ function isRecord(value) {
20
+ return !!value && typeof value === 'object' && !Array.isArray(value);
21
+ }
22
+ function internalRpcError() {
23
+ return new ProtocolError(ProtocolErrorCode.InternalError, 'Internal error');
24
+ }
25
+ export class TaskInputRunner {
26
+ store;
27
+ options;
28
+ clock;
29
+ humanRelay;
30
+ humanRelayGate;
31
+ contextFields;
32
+ devMode;
33
+ onError;
34
+ dueTaskStop;
35
+ constructor(deps) {
36
+ this.store = deps.store;
37
+ this.options = deps.options;
38
+ this.clock = deps.clock;
39
+ this.humanRelay = deps.humanRelay;
40
+ this.humanRelayGate = deps.humanRelayGate;
41
+ this.contextFields = deps.contextFields;
42
+ this.devMode = deps.devMode;
43
+ this.onError = deps.onError;
44
+ this.dueTaskStop = deps.dueTaskStop;
45
+ }
46
+ /**
47
+ * Rebind a background relay job's `RelayCall` to the task-owned context, signal, and cloned
48
+ * verified credentials so `isVerifiedCredentials` stays valid and `context.signal` stays live
49
+ * after `CreateTaskResult` closes the creating HTTP response (`spec/tasks.md`).
50
+ */
51
+ rebindRelayGate(gate, taskContext, verifiedCredentials) {
52
+ const credentials = (verifiedCredentials ?? taskContext.credentials);
53
+ const relayContext = {
54
+ ...withoutApprovalRelay(taskContext),
55
+ ...(gate.actor ? { actor: { ...gate.actor } } : {}),
56
+ };
57
+ if (this.contextFields?.length) {
58
+ applyContextFields(this.contextFields, relayContext, gate.call.command, {
59
+ devMode: this.devMode,
60
+ onError: (error) => {
61
+ try {
62
+ const returned = this.onError?.(error instanceof Error ? error : new Error(String(error)));
63
+ if (returned instanceof Promise)
64
+ returned.catch(() => { });
65
+ }
66
+ catch { }
67
+ },
68
+ });
69
+ }
70
+ gate.call = {
71
+ ...gate.call,
72
+ ...(credentials !== undefined ? { credentials } : {}),
73
+ context: relayContext,
74
+ };
75
+ }
76
+ async precheckHostVerified(command, rawInput, validatedData, callContext, actor, boundPrincipal) {
77
+ const name = command.name;
78
+ const relay = this.humanRelay;
79
+ if (!relay) {
80
+ return { kind: 'error', error: hostVerifiedUnrelayable([name], false) };
81
+ }
82
+ const channel = humanRelayChannel(callContext);
83
+ if (!channel?.modern) {
84
+ return { kind: 'error', error: hostVerifiedUnrelayable([name], true) };
85
+ }
86
+ const credentials = callContext.credentials;
87
+ let credsBinding;
88
+ try {
89
+ credsBinding = credentialsBinding(credentials);
90
+ }
91
+ catch {
92
+ throw internalRpcError();
93
+ }
94
+ let validatedCanonical;
95
+ let digest;
96
+ try {
97
+ validatedCanonical = canonicalJson(validatedData);
98
+ digest = createHash('sha256').update(validatedCanonical, 'utf8').digest('base64url');
99
+ }
100
+ catch (err) {
101
+ return {
102
+ kind: 'error',
103
+ error: {
104
+ code: ErrorCodes.VALIDATION_ERROR,
105
+ message: err instanceof Error ? err.message : 'Input has no canonical JSON form',
106
+ suggestion: 'Pass plain JSON input: integers within ±2^53',
107
+ retryable: false,
108
+ },
109
+ };
110
+ }
111
+ const capabilities = channel.clientCapabilities;
112
+ const relayContext = {
113
+ ...withoutApprovalRelay(callContext),
114
+ ...(actor ? { actor: { ...actor } } : {}),
115
+ };
116
+ if (this.contextFields?.length) {
117
+ const invalidField = applyContextFields(this.contextFields, relayContext, name, {
118
+ devMode: this.devMode,
119
+ onError: (error) => {
120
+ try {
121
+ const returned = this.onError?.(error instanceof Error ? error : new Error(String(error)));
122
+ if (returned instanceof Promise)
123
+ returned.catch(() => { });
124
+ }
125
+ catch { }
126
+ },
127
+ });
128
+ if (invalidField?.error) {
129
+ return { kind: 'error', error: invalidField.error };
130
+ }
131
+ }
132
+ const call = {
133
+ command: name,
134
+ inputDigest: digest,
135
+ ...(actor ? { actor: { ...actor } } : {}),
136
+ ...(credentials !== undefined ? { credentials } : {}),
137
+ ...(capabilities !== undefined ? { clientCapabilities: capabilities } : {}),
138
+ input: validatedData,
139
+ context: relayContext,
140
+ principalBinding: () => boundPrincipal,
141
+ supportsUrlElicitation: () => allowsUrlElicitation(capabilities),
142
+ };
143
+ const isStopAnswer = channel.requestState !== undefined &&
144
+ (channel.relayAction === 'decline' || channel.relayAction === 'cancel');
145
+ if (isStopAnswer) {
146
+ this.humanRelayGate?.forgetPending?.(name, rawInput, callContext, boundPrincipal);
147
+ return { kind: 'error', error: confirmDeclinedError(name) };
148
+ }
149
+ const canUrl = call.supportsUrlElicitation();
150
+ // Without URL mode, pendingList answers first if installed (`spec/tasks.md`).
151
+ if (!canUrl && relay.pendingList !== undefined) {
152
+ if (typeof relay.pendingList !== 'function')
153
+ throw internalRpcError();
154
+ const found = await relay.pendingList(call);
155
+ if (found !== undefined) {
156
+ if (!isRecord(found) || typeof found.kind !== 'string')
157
+ throw internalRpcError();
158
+ switch (found.kind) {
159
+ case 'approved':
160
+ this.humanRelayGate?.forgetPending?.(name, rawInput, callContext, boundPrincipal);
161
+ return {
162
+ kind: 'approved',
163
+ approval: await prepareRelayApproval(relay, found.decisionId, call, name, digest, actor, credsBinding, validatedCanonical),
164
+ };
165
+ case 'declined':
166
+ this.humanRelayGate?.forgetPending?.(name, rawInput, callContext, boundPrincipal);
167
+ return { kind: 'error', error: confirmDeclinedError(name) };
168
+ case 'pending':
169
+ this.humanRelayGate?.rememberPendingList?.(name, rawInput, boundPrincipal, validatedCanonical);
170
+ return { kind: 'error', error: relayPendingListRefusal(name, found) };
171
+ case 'error':
172
+ if (!isRecord(found.error) ||
173
+ typeof found.error.code !== 'string' ||
174
+ typeof found.error.message !== 'string') {
175
+ throw internalRpcError();
176
+ }
177
+ return { kind: 'error', error: found.error };
178
+ default:
179
+ throw internalRpcError();
180
+ }
181
+ }
182
+ }
183
+ // Carried relay answer (`accept` + `requestState`): call `resume` before task creation.
184
+ if (channel.relayAction === 'accept' && channel.requestState) {
185
+ const outcome = await relay.resume(channel.requestState, call);
186
+ if (!isRecord(outcome) || typeof outcome.kind !== 'string')
187
+ throw internalRpcError();
188
+ switch (outcome.kind) {
189
+ case 'approved':
190
+ this.humanRelayGate?.forgetPending?.(name, rawInput, callContext, boundPrincipal);
191
+ return {
192
+ kind: 'approved',
193
+ approval: await prepareRelayApproval(relay, outcome.decisionId, call, name, digest, actor, credsBinding, validatedCanonical),
194
+ };
195
+ case 'declined':
196
+ this.humanRelayGate?.forgetPending?.(name, rawInput, callContext, boundPrincipal);
197
+ return { kind: 'error', error: confirmDeclinedError(name) };
198
+ case 'pending': {
199
+ if (!canUrl) {
200
+ return { kind: 'error', error: relayUrlRequiredError(name) };
201
+ }
202
+ const { prompt } = buildRelayPromptRequest(outcome.prompt);
203
+ return {
204
+ kind: 'ask',
205
+ gate: {
206
+ relay,
207
+ call,
208
+ digest,
209
+ actor,
210
+ credsBinding,
211
+ validatedCanonical,
212
+ initialPrompt: prompt,
213
+ },
214
+ };
215
+ }
216
+ case 'invalid':
217
+ this.humanRelayGate?.forgetPending?.(name, rawInput, callContext, boundPrincipal);
218
+ break;
219
+ default:
220
+ throw internalRpcError();
221
+ }
222
+ }
223
+ if (!canUrl) {
224
+ // Without URL mode and with no approving/pending/declining answer, call begin to let a
225
+ // host refusal surface, else refuse inline with CONFIRMATION_REQUIRED.
226
+ const begun = await relay.begin(call);
227
+ if (!isRecord(begun) || typeof begun.ok !== 'boolean')
228
+ throw internalRpcError();
229
+ if (!begun.ok) {
230
+ if (!isRecord(begun.error) ||
231
+ typeof begun.error.code !== 'string' ||
232
+ typeof begun.error.message !== 'string') {
233
+ throw internalRpcError();
234
+ }
235
+ return { kind: 'error', error: begun.error };
236
+ }
237
+ return { kind: 'error', error: relayUrlRequiredError(name) };
238
+ }
239
+ // URL mode declared: defer `relay.begin` until the runner runs after `store.create`.
240
+ return {
241
+ kind: 'ask',
242
+ gate: {
243
+ relay,
244
+ call,
245
+ digest,
246
+ actor,
247
+ credsBinding,
248
+ validatedCanonical,
249
+ },
250
+ };
251
+ }
252
+ createTaskApprovalRelay(job, snapshotCanonical, initialAnswers) {
253
+ let claimed = false;
254
+ let initialConsumed = false;
255
+ const readInitial = (bindings) => {
256
+ if (initialConsumed || !initialAnswers)
257
+ return { kind: 'missing' };
258
+ initialConsumed = true;
259
+ if (initialAnswers.declined.some((b) => bindings.includes(b))) {
260
+ return { kind: 'decline' };
261
+ }
262
+ const match = initialAnswers.accepted
263
+ .filter((item) => bindings.includes(item.binding))
264
+ .at(-1);
265
+ return match ? { kind: 'accept', ...match } : { kind: 'missing' };
266
+ };
267
+ return {
268
+ route() { },
269
+ claim(command) {
270
+ if (claimed || command !== job.commandName)
271
+ return false;
272
+ claimed = true;
273
+ return true;
274
+ },
275
+ async answer(bindings) {
276
+ return readInitial(bindings);
277
+ },
278
+ hold() { },
279
+ async answers() {
280
+ return { accepted: [], declined: [] };
281
+ },
282
+ holdSteps() { },
283
+ runInTask: (step) => this.runApprovalInTask(job, snapshotCanonical, readInitial, step),
284
+ };
285
+ }
286
+ async markHandlerStarted(job) {
287
+ const now = this.clock.now();
288
+ const due = this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, now, job.runDeadlineMs);
289
+ if (due !== undefined) {
290
+ job.running.stop(due);
291
+ return false;
292
+ }
293
+ if (job.running.reason !== undefined)
294
+ return false;
295
+ let applied;
296
+ try {
297
+ const res = await this.store.update(job.id, job.owner, { kind: 'handler-started', at: now });
298
+ applied = typeof res === 'boolean' ? res : undefined;
299
+ }
300
+ catch {
301
+ job.earlyOutcome = { kind: 'internal' };
302
+ return false;
303
+ }
304
+ if (applied === false) {
305
+ const current = await this.store.get(job.id, job.owner).catch(() => undefined);
306
+ if (!current || isTaskExpired(current, now)) {
307
+ job.running.stop('ttl-ended');
308
+ }
309
+ else if (isTerminalTaskStatus(current.status)) {
310
+ job.running.stop('lost');
311
+ }
312
+ else {
313
+ job.running.stop('cancelled');
314
+ }
315
+ return false;
316
+ }
317
+ if (applied === undefined) {
318
+ // Legacy store returning void: confirm the record accepted handler-started without cancel.
319
+ const current = await this.store.get(job.id, job.owner).catch(() => undefined);
320
+ if (!current || isTaskExpired(current, now)) {
321
+ job.running.stop('ttl-ended');
322
+ return false;
323
+ }
324
+ if (isTerminalTaskStatus(current.status)) {
325
+ job.running.stop('lost');
326
+ return false;
327
+ }
328
+ if (current.cancelRequested) {
329
+ job.running.stop('cancelled');
330
+ return false;
331
+ }
332
+ }
333
+ // Recheck stop signal and deadlines synchronously after the store await so a delayed
334
+ // `handler-started` acknowledgement never starts a handler after `driveTask` reported a
335
+ // retryable `not-started` timeout or token expiry.
336
+ const afterDue = job.running.reason ??
337
+ this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now(), job.runDeadlineMs);
338
+ if (afterDue !== undefined) {
339
+ job.running.stop(afterDue);
340
+ return false;
341
+ }
342
+ job.handlerStarted = true;
343
+ return true;
344
+ }
345
+ async askConfirmInTask(job) {
346
+ const prevWaiting = job.waitingForInput;
347
+ job.waitingForInput = true;
348
+ try {
349
+ const asked = await this.askQuestion(job, {
350
+ gate: 'confirm',
351
+ request: {
352
+ method: 'elicitation/create',
353
+ params: {
354
+ mode: 'form',
355
+ message: job.confirmPrompt ?? '',
356
+ requestedSchema: CONFIRM_REQUESTED_SCHEMA,
357
+ },
358
+ },
359
+ privateState: { gate: 'confirm' },
360
+ statusMessage: `Waiting for confirmation of '${job.commandName}'`,
361
+ questionDeadlineMs: this.clock.now() + DEFAULT_TASK_FORM_TIMEOUT_MS,
362
+ });
363
+ if (asked.kind === 'internal') {
364
+ const outcome = { kind: 'internal' };
365
+ job.earlyOutcome = outcome;
366
+ return { kind: 'outcome', outcome };
367
+ }
368
+ if (asked.kind === 'stopped') {
369
+ return {
370
+ kind: 'outcome',
371
+ outcome: { kind: 'stopped', stop: asked.stop, stage: 'not-started' },
372
+ };
373
+ }
374
+ if (asked.kind === 'unanswered') {
375
+ const outcome = {
376
+ kind: 'finished',
377
+ result: failure(confirmUnansweredError(job.commandName)),
378
+ };
379
+ job.earlyOutcome = outcome;
380
+ return { kind: 'outcome', outcome };
381
+ }
382
+ if (asked.response.action !== 'accept' || asked.response.content?.confirm !== true) {
383
+ const outcome = {
384
+ kind: 'finished',
385
+ result: failure(confirmDeclinedError(job.commandName)),
386
+ };
387
+ job.earlyOutcome = outcome;
388
+ return { kind: 'outcome', outcome };
389
+ }
390
+ job.confirmValidUntil = asked.askedAt + DEFAULT_TASK_FORM_TIMEOUT_MS;
391
+ let resumed;
392
+ try {
393
+ const res = await this.store.update(job.id, job.owner, {
394
+ kind: 'working',
395
+ at: this.clock.now(),
396
+ });
397
+ resumed = typeof res === 'boolean' ? res : undefined;
398
+ }
399
+ catch {
400
+ const outcome = { kind: 'internal' };
401
+ job.earlyOutcome = outcome;
402
+ return { kind: 'outcome', outcome };
403
+ }
404
+ if (resumed === false) {
405
+ job.running.stop('cancelled');
406
+ return {
407
+ kind: 'outcome',
408
+ outcome: { kind: 'stopped', stop: 'cancelled', stage: 'not-started' },
409
+ };
410
+ }
411
+ return { kind: 'accepted' };
412
+ }
413
+ finally {
414
+ job.waitingForInput = prevWaiting;
415
+ }
416
+ }
417
+ async runRelayGate(job, gate) {
418
+ const beginPrompt = async () => {
419
+ if (job.running.reason !== undefined) {
420
+ return {
421
+ kind: 'outcome',
422
+ outcome: { kind: 'stopped', stop: job.running.reason, stage: 'not-started' },
423
+ };
424
+ }
425
+ let begun;
426
+ try {
427
+ begun = await gate.relay.begin(gate.call);
428
+ }
429
+ catch {
430
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
431
+ }
432
+ if (job.running.reason !== undefined) {
433
+ return {
434
+ kind: 'outcome',
435
+ outcome: { kind: 'stopped', stop: job.running.reason, stage: 'not-started' },
436
+ };
437
+ }
438
+ if (!isRecord(begun) || typeof begun.ok !== 'boolean') {
439
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
440
+ }
441
+ if (!begun.ok) {
442
+ if (!isRecord(begun.error) ||
443
+ typeof begun.error.code !== 'string' ||
444
+ typeof begun.error.message !== 'string') {
445
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
446
+ }
447
+ return {
448
+ kind: 'outcome',
449
+ outcome: { kind: 'finished', result: failure(begun.error) },
450
+ };
451
+ }
452
+ try {
453
+ const built = buildRelayPromptRequest(begun.prompt);
454
+ return { kind: 'prompt', prompt: built.prompt, request: built.request };
455
+ }
456
+ catch {
457
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
458
+ }
459
+ };
460
+ const applyApproved = async (decisionId) => {
461
+ if (job.running.reason !== undefined) {
462
+ return { kind: 'stopped', stop: job.running.reason, stage: 'not-started' };
463
+ }
464
+ try {
465
+ const prepared = await prepareRelayApproval(gate.relay, decisionId, gate.call, job.commandName, gate.digest, gate.actor, gate.credsBinding, gate.validatedCanonical);
466
+ if (job.running.reason !== undefined) {
467
+ return { kind: 'stopped', stop: job.running.reason, stage: 'not-started' };
468
+ }
469
+ const nextContext = {
470
+ ...withoutApprovalRelay(job.context),
471
+ ...prepared.extra,
472
+ };
473
+ attachRelayEvidence(nextContext, prepared.evidence);
474
+ attachRelayValidatedInput(nextContext, job.commandName, job.validatedData);
475
+ attachRelayDispatchAdmission(nextContext, prepared.admission);
476
+ job.context = nextContext;
477
+ return undefined;
478
+ }
479
+ catch {
480
+ return { kind: 'internal' };
481
+ }
482
+ };
483
+ let current;
484
+ if (gate.initialPrompt) {
485
+ try {
486
+ current = buildRelayPromptRequest(gate.initialPrompt);
487
+ }
488
+ catch {
489
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
490
+ }
491
+ }
492
+ else {
493
+ const started = await beginPrompt();
494
+ if (started.kind === 'outcome')
495
+ return started;
496
+ current = { prompt: started.prompt, request: started.request };
497
+ }
498
+ for (;;) {
499
+ const prevWaiting = job.waitingForInput;
500
+ job.waitingForInput = true;
501
+ let asked;
502
+ try {
503
+ asked = await this.askQuestion(job, {
504
+ gate: 'relay',
505
+ request: current.request,
506
+ privateState: { gate: 'relay', state: current.prompt.state },
507
+ statusMessage: `Waiting for confirmation of '${job.commandName}'`,
508
+ questionDeadlineMs: job.runDeadlineMs,
509
+ });
510
+ if (asked.kind === 'internal') {
511
+ const outcome = { kind: 'internal' };
512
+ job.earlyOutcome = outcome;
513
+ return { kind: 'outcome', outcome };
514
+ }
515
+ if (asked.kind === 'stopped') {
516
+ return {
517
+ kind: 'outcome',
518
+ outcome: { kind: 'stopped', stop: asked.stop, stage: 'not-started' },
519
+ };
520
+ }
521
+ if (asked.kind === 'unanswered') {
522
+ const outcome = {
523
+ kind: 'finished',
524
+ result: failure(confirmUnansweredError(job.commandName)),
525
+ };
526
+ job.earlyOutcome = outcome;
527
+ return { kind: 'outcome', outcome };
528
+ }
529
+ if (asked.response.action !== 'accept') {
530
+ const outcome = {
531
+ kind: 'finished',
532
+ result: failure(confirmDeclinedError(job.commandName)),
533
+ };
534
+ job.earlyOutcome = outcome;
535
+ return { kind: 'outcome', outcome };
536
+ }
537
+ const resumed = await this.store.update(job.id, job.owner, {
538
+ kind: 'working',
539
+ at: this.clock.now(),
540
+ });
541
+ if (resumed === false) {
542
+ job.running.stop('cancelled');
543
+ return {
544
+ kind: 'outcome',
545
+ outcome: { kind: 'stopped', stop: 'cancelled', stage: 'not-started' },
546
+ };
547
+ }
548
+ }
549
+ finally {
550
+ job.waitingForInput = prevWaiting;
551
+ }
552
+ let stateToResume = current.prompt.state;
553
+ const askedUrl = current.prompt.url;
554
+ // Inner loop: handle `resume` and poll same-URL `Pending` without re-asking the person.
555
+ // Deadlines, token expiry, heartbeats and remote cancellation are checked at the top of
556
+ // each iteration BEFORE invoking `resume` so a single-use decision is never spent past
557
+ // expiry or cancellation. `waitingForInput` stays `false` while `relay.resume` /
558
+ // `approvedContext` / `begin` are awaited so `driveTask`'s watchdog supervises hung
559
+ // relay callbacks.
560
+ const prevInnerWaiting = job.waitingForInput;
561
+ try {
562
+ for (;;) {
563
+ const checkNow = this.clock.now();
564
+ if (job.running.reason !== undefined) {
565
+ return {
566
+ kind: 'outcome',
567
+ outcome: { kind: 'stopped', stop: job.running.reason, stage: 'not-started' },
568
+ };
569
+ }
570
+ const preStop = this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, checkNow);
571
+ if (preStop !== undefined) {
572
+ job.running.stop(preStop);
573
+ return {
574
+ kind: 'outcome',
575
+ outcome: { kind: 'stopped', stop: preStop, stage: 'not-started' },
576
+ };
577
+ }
578
+ if (checkNow >= job.runDeadlineMs) {
579
+ const outcome = {
580
+ kind: 'finished',
581
+ result: failure(confirmUnansweredError(job.commandName)),
582
+ };
583
+ job.earlyOutcome = outcome;
584
+ return { kind: 'outcome', outcome };
585
+ }
586
+ if (this.store.heartbeat) {
587
+ await this.store.heartbeat(job.id, job.owner, checkNow).catch(() => { });
588
+ }
589
+ try {
590
+ const stored = await this.store.get(job.id, job.owner);
591
+ if (!stored || isTaskExpired(stored, checkNow)) {
592
+ job.running.stop('ttl-ended');
593
+ return {
594
+ kind: 'outcome',
595
+ outcome: { kind: 'stopped', stop: 'ttl-ended', stage: 'not-started' },
596
+ };
597
+ }
598
+ if (isTerminalTaskStatus(stored.status)) {
599
+ job.running.stop('lost');
600
+ return {
601
+ kind: 'outcome',
602
+ outcome: { kind: 'stopped', stop: 'lost', stage: 'not-started' },
603
+ };
604
+ }
605
+ if (stored.cancelRequested) {
606
+ job.running.stop('cancelled');
607
+ return {
608
+ kind: 'outcome',
609
+ outcome: { kind: 'stopped', stop: 'cancelled', stage: 'not-started' },
610
+ };
611
+ }
612
+ }
613
+ catch {
614
+ // Transient read failure; recheck deadlines before calling resume.
615
+ }
616
+ const afterCheckNow = this.clock.now();
617
+ const postCheckStop = job.running.reason ??
618
+ this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, afterCheckNow);
619
+ if (postCheckStop !== undefined) {
620
+ job.running.stop(postCheckStop);
621
+ return {
622
+ kind: 'outcome',
623
+ outcome: { kind: 'stopped', stop: postCheckStop, stage: 'not-started' },
624
+ };
625
+ }
626
+ if (afterCheckNow >= job.runDeadlineMs) {
627
+ const outcome = {
628
+ kind: 'finished',
629
+ result: failure(confirmUnansweredError(job.commandName)),
630
+ };
631
+ job.earlyOutcome = outcome;
632
+ return { kind: 'outcome', outcome };
633
+ }
634
+ // Yield supervision to `driveTask` while awaiting the host relay callback.
635
+ job.waitingForInput = false;
636
+ let outcome;
637
+ try {
638
+ outcome = await gate.relay.resume(stateToResume, gate.call);
639
+ }
640
+ catch {
641
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
642
+ }
643
+ // Recheck stop signal and deadlines immediately after `resume` settles so a
644
+ // slow/late `resume` never invokes `relay.begin` or `relay.approvedContext` on
645
+ // an already-cancelled or expired task.
646
+ const postResumeStop = job.running.reason ??
647
+ this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, this.clock.now());
648
+ if (postResumeStop !== undefined) {
649
+ job.running.stop(postResumeStop);
650
+ return {
651
+ kind: 'outcome',
652
+ outcome: { kind: 'stopped', stop: postResumeStop, stage: 'not-started' },
653
+ };
654
+ }
655
+ // Clear same-URL pending wait now that `resume` resolved; the same-URL `pending`
656
+ // branch re-sets it before sleeping, while `approved` / `invalid` run under
657
+ // standard run-timeout semantics.
658
+ job.relayPendingWait = false;
659
+ if (!isRecord(outcome) || typeof outcome.kind !== 'string') {
660
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
661
+ }
662
+ if (outcome.kind === 'approved') {
663
+ const err = await applyApproved(outcome.decisionId);
664
+ if (err)
665
+ return { kind: 'outcome', outcome: err };
666
+ const cleared = await this.store.update(job.id, job.owner, {
667
+ kind: 'working',
668
+ at: this.clock.now(),
669
+ });
670
+ if (cleared === false) {
671
+ job.running.stop('cancelled');
672
+ return {
673
+ kind: 'outcome',
674
+ outcome: { kind: 'stopped', stop: 'cancelled', stage: 'not-started' },
675
+ };
676
+ }
677
+ return { kind: 'approved' };
678
+ }
679
+ if (outcome.kind === 'declined') {
680
+ return {
681
+ kind: 'outcome',
682
+ outcome: {
683
+ kind: 'finished',
684
+ result: failure(confirmDeclinedError(job.commandName)),
685
+ },
686
+ };
687
+ }
688
+ if (outcome.kind === 'invalid') {
689
+ const restarted = await beginPrompt();
690
+ if (restarted.kind === 'outcome')
691
+ return restarted;
692
+ current = { prompt: restarted.prompt, request: restarted.request };
693
+ break;
694
+ }
695
+ if (outcome.kind === 'pending') {
696
+ let nextBuilt;
697
+ try {
698
+ nextBuilt = buildRelayPromptRequest(outcome.prompt);
699
+ }
700
+ catch {
701
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
702
+ }
703
+ if (nextBuilt.prompt.url !== askedUrl) {
704
+ current = nextBuilt;
705
+ break;
706
+ }
707
+ // Same URL: stay `working` with a waiting statusMessage and wait until next poll.
708
+ // Hold `waitingForInput` across the sleep and set `relayPendingWait` so run-budget
709
+ // expiry resolves as `CONFIRMATION_REQUIRED (reason: 'unanswered')` even if
710
+ // `runDeadlineMs` hits while a subsequent `resume` poll is in flight.
711
+ job.waitingForInput = true;
712
+ job.relayPendingWait = true;
713
+ stateToResume = nextBuilt.prompt.state;
714
+ const now = this.clock.now();
715
+ await this.store
716
+ .update(job.id, job.owner, {
717
+ kind: 'progress',
718
+ message: `Waiting for decision on '${job.commandName}'`,
719
+ at: now,
720
+ })
721
+ .catch(() => { });
722
+ const nearest = Math.min(job.runDeadlineMs, job.ttlDeadlineMs, job.tokenDeadlineMs ?? Number.MAX_SAFE_INTEGER);
723
+ const waitMs = Math.min(this.options.checkIntervalMs, Math.max(1, nearest - now), MAX_TIMEOUT_MS);
724
+ await this.waitForTickOrSignal(job.running, waitMs);
725
+ continue;
726
+ }
727
+ return { kind: 'outcome', outcome: { kind: 'internal' } };
728
+ }
729
+ }
730
+ finally {
731
+ job.waitingForInput = prevInnerWaiting;
732
+ job.relayPendingWait = false;
733
+ }
734
+ }
735
+ }
736
+ async runApprovalInTask(job, snapshotCanonical, readInitial, step) {
737
+ const commandName = job.commandName;
738
+ if (snapshotCanonical === undefined || step.inputBinding !== snapshotCanonical) {
739
+ return failure({
740
+ code: ErrorCodes.APPROVAL_UNAVAILABLE,
741
+ message: `${commandName} needs a person's approval, and middleware changed its input before the approval step`,
742
+ suggestion: 'Do not retry: the input changed before the approval step, so the task cannot ask about it. Move middleware that modifies input before validation.',
743
+ retryable: false,
744
+ recovery: { kind: 'external' },
745
+ details: { reason: 'input-changed' },
746
+ });
747
+ }
748
+ const declined = () => failure({
749
+ code: ErrorCodes.APPROVAL_REQUIRED,
750
+ message: `The user did not approve ${commandName}`,
751
+ suggestion: 'Do not run this again without asking the user first; the user chose not to approve it.',
752
+ retryable: false,
753
+ recovery: { kind: 'stop' },
754
+ details: { summary: step.summary, reason: 'declined' },
755
+ });
756
+ const initial = readInitial(step.bindings);
757
+ if (initial.kind === 'decline')
758
+ return declined();
759
+ if (initial.kind === 'accept' && (await step.admit(initial))) {
760
+ return step.next({
761
+ via: 'elicitation',
762
+ key: initial.nonce,
763
+ expiresAt: initial.expiresAt,
764
+ });
765
+ }
766
+ let retryNote = initial.kind === 'accept'
767
+ ? 'The earlier approval expired or was already used; approve again to run it.'
768
+ : undefined;
769
+ for (;;) {
770
+ const hold = await step.makeHold(retryNote);
771
+ const prevWaiting = job.waitingForInput;
772
+ job.waitingForInput = true;
773
+ let outcome;
774
+ try {
775
+ outcome = await this.askApprovalInTask(job, hold);
776
+ if (outcome.kind === 'stopped') {
777
+ return failure({
778
+ code: ErrorCodes.COMMAND_CANCELLED,
779
+ message: `${commandName} was cancelled before approval completed`,
780
+ suggestion: 'Start the task again if the action is still needed.',
781
+ retryable: false,
782
+ });
783
+ }
784
+ if (outcome.kind === 'decline') {
785
+ const result = declined();
786
+ job.earlyOutcome = { kind: 'finished', result };
787
+ return result;
788
+ }
789
+ if (outcome.kind === 'unanswered') {
790
+ const result = failure({
791
+ code: ErrorCodes.APPROVAL_REQUIRED,
792
+ message: `${commandName} was not approved in time`,
793
+ suggestion: 'No one answered the approval in time; start the task again once the person is ready.',
794
+ retryable: false,
795
+ recovery: { kind: 'external' },
796
+ details: { summary: step.summary, reason: 'unanswered' },
797
+ });
798
+ job.earlyOutcome = { kind: 'finished', result };
799
+ return result;
800
+ }
801
+ if (outcome.kind === 'expired') {
802
+ retryNote = 'The earlier approval expired or was already used; approve again to run it.';
803
+ continue;
804
+ }
805
+ }
806
+ finally {
807
+ job.waitingForInput = prevWaiting;
808
+ }
809
+ if (step.changed()) {
810
+ return failure({
811
+ code: ErrorCodes.APPROVAL_UNAVAILABLE,
812
+ message: `${commandName}'s input changed while approval was being checked`,
813
+ suggestion: 'Pass a plain, immutable input object; do not mutate inputs or use getters that return different values.',
814
+ retryable: false,
815
+ details: { reason: 'input-changed' },
816
+ });
817
+ }
818
+ if (await step.admit(outcome.answer)) {
819
+ return step.next({
820
+ via: 'elicitation',
821
+ key: outcome.answer.nonce,
822
+ expiresAt: outcome.answer.expiresAt,
823
+ });
824
+ }
825
+ retryNote = 'The earlier approval expired or was already used; approve again to run it.';
826
+ }
827
+ }
828
+ async askQuestion(job, opts) {
829
+ const askedAt = this.clock.now();
830
+ const preStop = this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, askedAt);
831
+ if (preStop !== undefined) {
832
+ job.running.stop(preStop);
833
+ return { kind: 'stopped', stop: preStop };
834
+ }
835
+ if (job.running.reason !== undefined) {
836
+ return { kind: 'stopped', stop: job.running.reason };
837
+ }
838
+ const formCapMs = opts.request.params.mode === 'form'
839
+ ? askedAt + DEFAULT_TASK_FORM_TIMEOUT_MS
840
+ : Number.MAX_SAFE_INTEGER;
841
+ const effectiveExpiresAt = Math.min(opts.questionDeadlineMs, formCapMs, job.runDeadlineMs, job.ttlDeadlineMs, job.tokenDeadlineMs ?? Number.MAX_SAFE_INTEGER);
842
+ if (askedAt >= effectiveExpiresAt) {
843
+ return { kind: 'unanswered' };
844
+ }
845
+ const key = newQuestionKey(opts.gate, job.usedKeys);
846
+ let applied;
847
+ try {
848
+ const res = await this.store.update(job.id, job.owner, {
849
+ kind: 'input-requested',
850
+ key,
851
+ request: opts.request,
852
+ ...(opts.privateState !== undefined && { privateState: opts.privateState }),
853
+ expiresAt: effectiveExpiresAt,
854
+ statusMessage: opts.statusMessage,
855
+ at: askedAt,
856
+ });
857
+ applied = typeof res === 'boolean' ? res : undefined;
858
+ }
859
+ catch {
860
+ job.earlyOutcome = { kind: 'internal' };
861
+ return { kind: 'internal' };
862
+ }
863
+ if (applied === false) {
864
+ const current = await this.store.get(job.id, job.owner).catch(() => undefined);
865
+ if (!current || isTaskExpired(current, askedAt)) {
866
+ job.running.stop('ttl-ended');
867
+ return { kind: 'stopped', stop: 'ttl-ended' };
868
+ }
869
+ if (isTerminalTaskStatus(current.status)) {
870
+ job.running.stop('lost');
871
+ return { kind: 'stopped', stop: 'lost' };
872
+ }
873
+ job.running.stop('cancelled');
874
+ return { kind: 'stopped', stop: 'cancelled' };
875
+ }
876
+ const prevWaiting = job.waitingForInput;
877
+ job.waitingForInput = true;
878
+ try {
879
+ for (;;) {
880
+ const now = this.clock.now();
881
+ if (job.running.reason !== undefined) {
882
+ return { kind: 'stopped', stop: job.running.reason };
883
+ }
884
+ const hardStop = this.dueTaskStop(job.tokenDeadlineMs, job.ttlDeadlineMs, now);
885
+ if (hardStop !== undefined) {
886
+ job.running.stop(hardStop);
887
+ return { kind: 'stopped', stop: hardStop };
888
+ }
889
+ if (this.store.heartbeat) {
890
+ await this.store.heartbeat(job.id, job.owner, now).catch(() => { });
891
+ }
892
+ try {
893
+ const current = await this.store.get(job.id, job.owner);
894
+ if (!current || isTaskExpired(current, now)) {
895
+ job.running.stop('ttl-ended');
896
+ return { kind: 'stopped', stop: 'ttl-ended' };
897
+ }
898
+ if (isTerminalTaskStatus(current.status)) {
899
+ job.running.stop('lost');
900
+ return { kind: 'stopped', stop: 'lost' };
901
+ }
902
+ if (current.cancelRequested) {
903
+ job.running.stop('cancelled');
904
+ return { kind: 'stopped', stop: 'cancelled' };
905
+ }
906
+ if (current.answeredInput && current.answeredInput.key === key) {
907
+ return { kind: 'answered', response: current.answeredInput.response, askedAt };
908
+ }
909
+ }
910
+ catch {
911
+ // Transient store failure: retry on next tick.
912
+ }
913
+ if (now >= effectiveExpiresAt) {
914
+ return { kind: 'unanswered' };
915
+ }
916
+ const until = Math.max(1, effectiveExpiresAt - now);
917
+ const waitMs = Math.min(this.options.checkIntervalMs, until, MAX_TIMEOUT_MS);
918
+ await this.waitForTickOrSignal(job.running, waitMs);
919
+ }
920
+ }
921
+ finally {
922
+ job.waitingForInput = prevWaiting;
923
+ }
924
+ }
925
+ waitForTickOrSignal(running, waitMs) {
926
+ return new Promise((resolve) => {
927
+ if (running.reason !== undefined) {
928
+ resolve();
929
+ return;
930
+ }
931
+ let settled = false;
932
+ const done = () => {
933
+ if (settled)
934
+ return;
935
+ settled = true;
936
+ clearTimeout(timer);
937
+ unsubscribe();
938
+ resolve();
939
+ };
940
+ const unsubscribe = running.onInput(done);
941
+ const timer = setTimeout(done, waitMs);
942
+ });
943
+ }
944
+ async askApprovalInTask(job, hold) {
945
+ const asked = await this.askQuestion(job, {
946
+ gate: 'approval',
947
+ request: {
948
+ method: 'elicitation/create',
949
+ params: {
950
+ mode: 'form',
951
+ message: hold.message,
952
+ requestedSchema: APPROVAL_REQUESTED_SCHEMA,
953
+ },
954
+ },
955
+ privateState: {
956
+ gate: 'approval',
957
+ nonce: hold.nonce,
958
+ expiresAt: hold.expiresAt,
959
+ },
960
+ statusMessage: `Waiting for approval of '${job.commandName}'`,
961
+ questionDeadlineMs: Math.min(hold.expiresAt, this.clock.now() + DEFAULT_TASK_FORM_TIMEOUT_MS),
962
+ });
963
+ if (asked.kind === 'internal' || asked.kind === 'stopped') {
964
+ return { kind: 'stopped' };
965
+ }
966
+ if (asked.kind === 'unanswered') {
967
+ return { kind: 'unanswered' };
968
+ }
969
+ if (asked.response.action !== 'accept' || asked.response.content?.approve !== true) {
970
+ return { kind: 'decline' };
971
+ }
972
+ const approvalFormDeadline = Math.min(hold.expiresAt, asked.askedAt + DEFAULT_TASK_FORM_TIMEOUT_MS);
973
+ let resumed;
974
+ try {
975
+ const res = await this.store.update(job.id, job.owner, {
976
+ kind: 'working',
977
+ at: this.clock.now(),
978
+ });
979
+ resumed = typeof res === 'boolean' ? res : undefined;
980
+ }
981
+ catch {
982
+ job.earlyOutcome = { kind: 'internal' };
983
+ return { kind: 'stopped' };
984
+ }
985
+ if (resumed === false) {
986
+ job.running.stop('cancelled');
987
+ return { kind: 'stopped' };
988
+ }
989
+ if (this.clock.now() >= approvalFormDeadline) {
990
+ return { kind: 'expired' };
991
+ }
992
+ // If an earlier confirmation stopped counting while the approval waited, ask confirmation
993
+ // again under a new key before admitting the approval (`spec/tasks.md`, "How long a question waits").
994
+ if (job.confirmValidUntil !== undefined && this.clock.now() >= job.confirmValidUntil) {
995
+ const reconfirmed = await this.askConfirmInTask(job);
996
+ if (reconfirmed.kind === 'outcome') {
997
+ job.earlyOutcome ??= reconfirmed.outcome;
998
+ return { kind: 'stopped' };
999
+ }
1000
+ // Every form question stops counting ten minutes after it was asked, including if
1001
+ // re-asking confirmation waited past the approval form's own ten-minute window.
1002
+ if (this.clock.now() >= approvalFormDeadline) {
1003
+ return { kind: 'expired' };
1004
+ }
1005
+ }
1006
+ return {
1007
+ kind: 'accept',
1008
+ answer: {
1009
+ binding: hold.binding,
1010
+ nonce: hold.nonce,
1011
+ expiresAt: hold.expiresAt,
1012
+ mac: hold.mac,
1013
+ },
1014
+ };
1015
+ }
1016
+ }
1017
+ //# sourceMappingURL=tasks-input-runner.js.map