@zq-silk/yui 0.13.7 → 0.13.9

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 (78) hide show
  1. package/ARCHITECTURE.md +40 -4
  2. package/README.md +23 -4
  3. package/dist/cli/commandCatalog.js +21 -2
  4. package/dist/cli/updatePorts.js +4 -4
  5. package/dist/cli.js +43 -14
  6. package/dist/commands/agentCommands.js +1 -1
  7. package/dist/commands/configCommands.js +1 -86
  8. package/dist/commands/executionAuditCommands.js +17 -16
  9. package/dist/commands/globalRoleCommands.js +4 -4
  10. package/dist/commands/sessionCommands.js +2 -6
  11. package/dist/commands/taskActor.js +1 -2
  12. package/dist/commands/taskCommands.js +93 -21
  13. package/dist/commands/taskContextCommand.js +1 -1
  14. package/dist/commands/taskExecutionCommands.js +0 -5
  15. package/dist/commands/taskOverviewCommand.js +5 -1
  16. package/dist/commands/taskRoleRuntimeStatus.js +3 -16
  17. package/dist/config/configCatalog.js +1 -6
  18. package/dist/config/yuiConfig.js +0 -79
  19. package/dist/context/sessionBootstrapManifest.js +26 -23
  20. package/dist/controller/clientRuntime.js +40 -3
  21. package/dist/controller/controller.js +29 -54
  22. package/dist/controller/fileSchedulerStoreAdapter.js +372 -1117
  23. package/dist/controller/runtime.js +12 -5
  24. package/dist/controller/runtimeHookRunFence.js +3 -9
  25. package/dist/controller/runtimeLaunchCoordinator.js +44 -67
  26. package/dist/controller/structuredProviderObservation.js +18 -5
  27. package/dist/coordination/workMailbox.js +4 -4
  28. package/dist/execution/executionHealth.js +1 -1
  29. package/dist/executor/agentExecutor.js +103 -93
  30. package/dist/executor/executorRegistry.js +8 -20
  31. package/dist/executor/fileRoleLaunchPlanner.js +26 -93
  32. package/dist/executor/turnCompletion.js +5 -5
  33. package/dist/lifecycle/exactRunTerminalization.js +2 -4
  34. package/dist/observability/executionAudit.js +40 -94
  35. package/dist/operator/operatorSessionHistory.js +7 -5
  36. package/dist/output/rolePresentation.js +0 -1
  37. package/dist/repository/taskWorkspacePreparer.js +0 -1
  38. package/dist/role/role.js +13 -21
  39. package/dist/run/agentRun.js +4 -54
  40. package/dist/runtime/agentDriver.js +2 -0
  41. package/dist/runtime/agentError.js +114 -0
  42. package/dist/runtime/agentHost.js +55 -82
  43. package/dist/runtime/builtinAgentDrivers.js +21 -9
  44. package/dist/runtime/builtinAgentErrorMappers.js +150 -0
  45. package/dist/runtime/exactControlPlane.js +6 -12
  46. package/dist/runtime/index.js +1 -2
  47. package/dist/runtime/launchBroker.js +5 -19
  48. package/dist/runtime/lifecycleReservation.js +20 -4
  49. package/dist/runtime/providerRuntimeIdentity.js +11 -19
  50. package/dist/runtime/runtimeBinding.js +0 -27
  51. package/dist/runtime/runtimeObservation.js +7 -16
  52. package/dist/runtime/runtimeSessionCandidate.js +3 -10
  53. package/dist/runtime/sessionLaunchRequest.js +1 -2
  54. package/dist/runtime/sessionReconciliation.js +2 -2
  55. package/dist/runtime/structuredProviderHost.js +44 -79
  56. package/dist/runtime/taskRuntimeIsolation.js +0 -7
  57. package/dist/runtime/tmuxAdapters.js +6 -49
  58. package/dist/scheduler/activeRoleRunDelivery.js +220 -178
  59. package/dist/scheduler/activeTaskProgress.js +1 -4
  60. package/dist/scheduler/leaderWakeupProcessor.js +123 -88
  61. package/dist/scheduler/roleRunLiveness.js +4 -1
  62. package/dist/scheduler/roleRunStall.js +10 -14
  63. package/dist/scheduler/wakeReason.js +4 -0
  64. package/dist/storage/migration/productionRegistry.js +475 -0
  65. package/dist/storage/sqliteSchema.js +54 -2
  66. package/dist/storage/sqliteStore.js +11 -44
  67. package/dist/storage/taskStore.js +8 -36
  68. package/dist/web/webSnapshot.js +3 -0
  69. package/i18n/README.zh-CN.md +11 -3
  70. package/package.json +1 -1
  71. package/skills/yui-leader/SKILL.md +30 -8
  72. package/skills/yui-operator/SKILL.md +14 -6
  73. package/skills/yui-runtime/SKILL.md +11 -8
  74. package/dist/lifecycle/providerErrorClass.js +0 -152
  75. package/dist/run/providerRetry.js +0 -226
  76. package/dist/run/providerRetryConfig.js +0 -27
  77. package/dist/runtime/providerErrorCodes.js +0 -278
  78. package/dist/runtime/providerRecoveryDecision.js +0 -55
@@ -1,6 +1,5 @@
1
1
  import { validateEffectiveLaunchSnapshot } from "../executor/effectiveLaunch.js";
2
2
  import { formatAgentRunReceiptId, validateTaskRecordReference } from "../task/taskRecordReference.js";
3
- import { prepareProviderRetryDispatch, validateAgentRunProviderRetry } from "./providerRetry.js";
4
3
  import { validateYieldReceipt } from "./yieldReceipt.js";
5
4
  import { validateAgentRunControlRequest } from "./runControlRequest.js";
6
5
  import { validateManagedWorkspace } from "../worktree/managedWorkspace.js";
@@ -30,7 +29,7 @@ export function createAgentRun(id, taskId, roleName, mode, assignment, now, cont
30
29
  })
31
30
  : validateRunAssignment(assignment);
32
31
  return {
33
- schemaVersion: 9,
32
+ schemaVersion: 10,
34
33
  id: requireSafeIdentity(id, "Agent run id"),
35
34
  taskId: requireSafeIdentity(taskId, "Task id"),
36
35
  roleName: requireSafeIdentity(roleName, "Role name"),
@@ -104,8 +103,8 @@ export function markAgentRunDelivered(run, now) {
104
103
  };
105
104
  }
106
105
  export function validateAgentRun(run) {
107
- if (run.schemaVersion !== 9)
108
- throw new Error("Agent run must use schemaVersion 9.");
106
+ if (run.schemaVersion !== 10)
107
+ throw new Error("Agent run must use schemaVersion 10.");
109
108
  validateTaskRecordReference({ taskId: run.taskId, localId: run.id }, "agentRun");
110
109
  requireSafeIdentity(run.roleName, "Role name");
111
110
  if (run.mode !== "new" && run.mode !== "resume") {
@@ -266,12 +265,6 @@ export function validateAgentRun(run) {
266
265
  }
267
266
  }
268
267
  }
269
- if (run.providerRetry !== undefined) {
270
- validateAgentRunProviderRetry(run.providerRetry);
271
- if (run.status !== "active") {
272
- throw new Error("A terminal Agent run cannot carry a providerRetry projection.");
273
- }
274
- }
275
268
  if (run.controlRequest !== undefined) {
276
269
  validateAgentRunControlRequest(run.controlRequest);
277
270
  if (run.status !== "active") {
@@ -304,60 +297,17 @@ function finishAgentRun(run, status, summary, now) {
304
297
  updatedAt: timestamp,
305
298
  endedAt: timestamp
306
299
  };
307
- // A terminal Run no longer waits for a retry; the projection is cleared so
308
- // old and new readers agree the Run is settled.
309
- if (terminal.providerRetry !== undefined) {
310
- delete terminal.providerRetry;
311
- }
312
300
  if (terminal.controlRequest !== undefined)
313
301
  delete terminal.controlRequest;
314
302
  return terminal;
315
303
  }
316
- /**
317
- * Attaches (or advances) the Issue 04 in-place retry projection on an active
318
- * Run. The Run stays `active`; only the projection changes.
319
- */
320
- export function withProviderRetry(run, retry) {
321
- if (run.status !== "active") {
322
- throw new Error(`Cannot schedule provider retry on a terminal Agent run: ${run.id}.`);
323
- }
324
- return validateAgentRun({ ...run, providerRetry: retry });
325
- }
326
- /**
327
- * Reopens an active retry-waiting Run for another in-place attempt on its
328
- * original Native Session. The original Run transport/acceptance timestamps
329
- * remain historical facts; the new delivery receipt and `dispatching` retry
330
- * state make the delivery path send only the short continuation envelope.
331
- */
332
- export function reopenRunForProviderRetry(run, receiptId, now, mode = "resume") {
333
- if (run.status !== "active" || run.providerRetry === undefined) {
334
- throw new Error(`Agent run is not waiting for a provider retry: ${run.id}.`);
335
- }
336
- const timestamp = now.toISOString();
337
- const { providerRetry, ...rest } = run;
338
- return validateAgentRun({
339
- ...rest,
340
- mode,
341
- deliveryReceiptId: receiptId,
342
- updatedAt: timestamp,
343
- providerRetry: prepareProviderRetryDispatch(providerRetry, receiptId, now)
344
- });
345
- }
346
- /** Any exact correlated provider progress ends the active consecutive-failure episode. */
347
- export function clearProviderRetryOnProgress(run) {
348
- if (run.providerRetry === undefined)
349
- return run;
350
- const { providerRetry: _providerRetry, ...rest } = run;
351
- return validateAgentRun(rest);
352
- }
353
304
  export function agentRunDeliveryReceiptId(run) {
354
305
  return run.deliveryReceiptId
355
306
  ?? run.controlRequest?.receiptId
356
- ?? run.providerRetry?.lastRetryReceiptId
357
307
  ?? formatAgentRunReceiptId(run.taskId, run.id);
358
308
  }
359
309
  export function withAgentRunControlRequest(run, request, now) {
360
- if (run.status !== "active" || run.providerRetry !== undefined) {
310
+ if (run.status !== "active") {
361
311
  throw new Error(`Agent run cannot accept a control request: ${run.id}.`);
362
312
  }
363
313
  return validateAgentRun({
@@ -233,6 +233,7 @@ export class AgentDriverRegistry {
233
233
  }
234
234
  if (typeof input.runtime.nativeSessionId !== "function"
235
235
  || typeof input.runtime.nativeTurnId !== "function"
236
+ || typeof input.runtime.mapError !== "function"
236
237
  || typeof input.runtime.mapHook !== "function"
237
238
  || typeof input.runtime.classifyHook !== "function"
238
239
  || (input.runtime.observer !== undefined
@@ -249,6 +250,7 @@ export class AgentDriverRegistry {
249
250
  runtime: Object.freeze({
250
251
  nativeSessionId: input.runtime.nativeSessionId,
251
252
  nativeTurnId: input.runtime.nativeTurnId,
253
+ mapError: input.runtime.mapError,
252
254
  mapHook: input.runtime.mapHook,
253
255
  classifyHook: input.runtime.classifyHook,
254
256
  ...(input.runtime.observer === undefined
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Provider-neutral Agent failure facts.
3
+ *
4
+ * Drivers recognize provider-native failures. Core persists the resulting
5
+ * facts and routes them to an Agent; it does not attach a recovery policy.
6
+ * `unknown` is the required fallback and the complete native payload is always
7
+ * retained in `raw`.
8
+ */
9
+ export const AGENT_ERROR_CATEGORIES = Object.freeze([
10
+ "availability",
11
+ "rate-limit",
12
+ "transport",
13
+ "access",
14
+ "invalid-request",
15
+ "context",
16
+ "session",
17
+ "runtime",
18
+ "conflict",
19
+ "cancelled",
20
+ "unknown"
21
+ ]);
22
+ export function standardAgentError(input) {
23
+ const classification = input.classification ?? UNKNOWN_AGENT_ERROR_CLASSIFICATION;
24
+ const retryAfterMs = input.retryAfterMs;
25
+ if (retryAfterMs !== undefined
26
+ && (!Number.isSafeInteger(retryAfterMs) || retryAfterMs < 0)) {
27
+ throw new Error("Agent error retryAfterMs must be a non-negative safe integer.");
28
+ }
29
+ return Object.freeze({
30
+ source: input.source,
31
+ phase: input.phase,
32
+ category: classification.category,
33
+ code: requiredErrorText(classification.code, "Agent error code"),
34
+ message: requiredErrorText(input.message, "Agent error message"),
35
+ raw: requiredErrorText(input.raw, "Agent error raw payload"),
36
+ inputDisposition: input.inputDisposition
37
+ ?? classification.inputDisposition
38
+ ?? "unknown",
39
+ sessionDisposition: input.sessionDisposition
40
+ ?? classification.sessionDisposition
41
+ ?? "unknown",
42
+ ...(retryAfterMs === undefined ? {} : { retryAfterMs })
43
+ });
44
+ }
45
+ export const UNKNOWN_AGENT_ERROR_CLASSIFICATION = Object.freeze({
46
+ category: "unknown",
47
+ code: "unknown"
48
+ });
49
+ export function isAgentErrorCategory(value) {
50
+ return typeof value === "string"
51
+ && AGENT_ERROR_CATEGORIES.includes(value);
52
+ }
53
+ export function isStandardAgentError(value) {
54
+ if (value === null || typeof value !== "object" || Array.isArray(value))
55
+ return false;
56
+ const error = value;
57
+ return ["provider", "driver", "host", "yui"].includes(error.source ?? "")
58
+ && [
59
+ "host-start",
60
+ "session-start",
61
+ "session-restore",
62
+ "turn-submit",
63
+ "turn-execute",
64
+ "turn-reconcile",
65
+ "host-stop"
66
+ ].includes(error.phase ?? "")
67
+ && isAgentErrorCategory(error.category)
68
+ && isErrorText(error.code)
69
+ && isErrorText(error.message)
70
+ && isErrorText(error.raw)
71
+ && ["accepted", "not-accepted", "unknown"].includes(error.inputDisposition ?? "")
72
+ && ["recoverable", "unrecoverable", "unknown"].includes(error.sessionDisposition ?? "")
73
+ && (error.retryAfterMs === undefined
74
+ || (Number.isSafeInteger(error.retryAfterMs) && error.retryAfterMs >= 0));
75
+ }
76
+ export function serializeAgentErrorRaw(value) {
77
+ if (typeof value === "string")
78
+ return requiredErrorText(value, "Agent error raw payload");
79
+ if (value === undefined)
80
+ return "Agent operation failed without an error payload.";
81
+ try {
82
+ const seen = new WeakSet();
83
+ const serialized = JSON.stringify(value, (_key, member) => {
84
+ if (typeof member === "bigint")
85
+ return member.toString();
86
+ if (member !== null && typeof member === "object") {
87
+ if (seen.has(member))
88
+ return "[Circular]";
89
+ seen.add(member);
90
+ if (member instanceof Error) {
91
+ return Object.fromEntries(Object.getOwnPropertyNames(member).map((name) => [
92
+ name,
93
+ member[name]
94
+ ]));
95
+ }
96
+ }
97
+ return member;
98
+ });
99
+ return serialized === undefined
100
+ ? String(value)
101
+ : requiredErrorText(serialized, "Agent error raw payload");
102
+ }
103
+ catch {
104
+ return requiredErrorText(String(value), "Agent error raw payload");
105
+ }
106
+ }
107
+ function isErrorText(value) {
108
+ return typeof value === "string" && value.trim().length > 0 && !value.includes("\0");
109
+ }
110
+ function requiredErrorText(value, label) {
111
+ if (!isErrorText(value))
112
+ throw new Error(`${label} is required.`);
113
+ return value;
114
+ }
@@ -16,7 +16,8 @@ import { validateRuntimeProcessExitObservation } from "./processExitObservation.
16
16
  import { persistRuntimeProcessExitObservation, replayRuntimeProcessExitOutbox } from "./processExitOutbox.js";
17
17
  import { readRuntimeStopReceipt, removeRuntimeStopReceipt } from "./runtimeStopReceipt.js";
18
18
  import { AGENT_HOST_CONTROL_TIMEOUT_MS, AGENT_HOST_READY_TIMEOUT_MS } from "./runtimeDeadlines.js";
19
- export const AGENT_HOST_CONTROL_PROTOCOL = "yui-agent-host/v2";
19
+ import { serializeAgentErrorRaw } from "./agentError.js";
20
+ export const AGENT_HOST_CONTROL_PROTOCOL = "yui-agent-host/v3";
20
21
  const HOST_CONTROL_MAX_BYTES = 32 * 1024;
21
22
  const CODEX_CLIENT_STABLE_MS = 5_000;
22
23
  const MAX_CONSECUTIVE_CODEX_DISCONNECTS = 3;
@@ -146,7 +147,7 @@ export async function runAgentHost(input) {
146
147
  schemaVersion: 1,
147
148
  adapterId: "codex",
148
149
  transport: "codex-app-server-proxy",
149
- kind: "ensure",
150
+ kind: "restore",
150
151
  mode: "resume",
151
152
  nativeSessionId: disconnectedSession.nativeSessionId,
152
153
  ...(previousControl.sessionTitle === undefined
@@ -351,7 +352,7 @@ export async function runAgentHost(input) {
351
352
  throw new Error("Agent Host still owns an unsettled Provider Turn.");
352
353
  }
353
354
  const requestedAuthority = validateProviderAuthorityFence(providerControl.authority);
354
- const replacesCurrentConversation = session !== undefined && providerControl.kind === "new";
355
+ const replacesCurrentConversation = session !== undefined && providerControl.kind === "start";
355
356
  if (replacesCurrentConversation) {
356
357
  throw new Error("Agent Host cannot replace a live Provider Session; stop it before starting a fresh Session.");
357
358
  }
@@ -364,9 +365,6 @@ export async function runAgentHost(input) {
364
365
  updateSnapshot(hostSnapshot("starting", {
365
366
  launchId: next.launchId,
366
367
  adapterId: providerControl.adapterId,
367
- ...(providerControl.initialTurn === undefined
368
- ? {}
369
- : { attemptId: providerControl.initialTurn.attemptId }),
370
368
  ...(session === undefined ? {} : {
371
369
  processInstanceId: session.processInstanceId,
372
370
  nativeSessionId: session.nativeSessionId,
@@ -374,8 +372,6 @@ export async function runAgentHost(input) {
374
372
  }),
375
373
  ...authorityFields()
376
374
  }));
377
- let providerAcceptedAttemptId;
378
- let durableInitialTurn;
379
375
  try {
380
376
  if (session !== undefined) {
381
377
  if (session.adapterId !== providerControl.adapterId
@@ -390,7 +386,7 @@ export async function runAgentHost(input) {
390
386
  conversationRecoverability = providerControl.adapterId === "codex"
391
387
  ? "recoverable"
392
388
  : "unknown";
393
- if (providerControl.kind === "ensure" && providerControl.ownedTurn !== undefined) {
389
+ if (providerControl.kind === "restore" && providerControl.ownedTurn !== undefined) {
394
390
  activeTurnPayload = next;
395
391
  activeTurnAttemptId = providerControl.ownedTurn.attemptId;
396
392
  activeNativeTurnId = providerControl.ownedTurn.turnId;
@@ -416,58 +412,24 @@ export async function runAgentHost(input) {
416
412
  recoverability: conversationRecoverability,
417
413
  observedAt: new Date().toISOString()
418
414
  });
419
- let receipt;
420
- if (providerControl.initialTurn !== undefined) {
421
- durableInitialTurn = hostTurnControlParams(next, session.nativeSessionId, requestedAuthority, providerControl.initialTurn.attemptId);
422
- await beginDurableProviderTurn(input.home, durableInitialTurn);
423
- activeTurnPayload = next;
424
- activeTurnAttemptId = providerControl.initialTurn.attemptId;
425
- activeNativeTurnId = undefined;
426
- try {
427
- receipt = await session.submitTurn(providerControl.initialTurn);
428
- providerAcceptedAttemptId = receipt.attemptId;
429
- activeNativeTurnId = receipt.nativeTurnId;
430
- }
431
- catch (error) {
432
- await resolveProviderTurnSubmission(input.home, durableInitialTurn, error);
433
- throw error;
434
- }
435
- }
436
- if (receipt !== undefined) {
437
- conversationRecoverability = "recoverable";
438
- try {
439
- await publishStructuredProviderAccepted({
440
- home: input.home,
441
- environment: next.environment,
442
- activationId: activationId ?? next.launchId,
443
- receipt
444
- });
445
- }
446
- catch (error) {
447
- await resolveProviderTurnSubmission(input.home, durableInitialTurn, new ProviderDeliveryUnknownError(`Provider accepted input but its durable acknowledgement could not be confirmed: ${errorText(error)}`, receipt.attemptId));
448
- throw error;
449
- }
450
- }
451
- const ensuredOwnedTurn = providerControl.kind === "ensure"
415
+ const restoredOwnedTurn = providerControl.kind === "restore"
452
416
  ? providerControl.ownedTurn
453
417
  : undefined;
454
- const providerState = receipt !== undefined || ensuredOwnedTurn !== undefined
418
+ const providerState = restoredOwnedTurn !== undefined
455
419
  ? "ready"
456
420
  : session.activeTurnId === undefined ? "idle" : "busy";
457
421
  updateSnapshot(hostSnapshot(providerState, {
458
422
  launchId: next.launchId,
459
423
  adapterId: providerControl.adapterId,
460
424
  processInstanceId: session.processInstanceId,
461
- nativeSessionId: receipt?.nativeSessionId ?? session.nativeSessionId,
462
- conversationId: receipt?.conversationId ?? session.conversationId,
463
- ...(receipt !== undefined
464
- ? { attemptId: receipt.attemptId, nativeTurnId: receipt.nativeTurnId }
465
- : ensuredOwnedTurn === undefined
466
- ? {}
467
- : {
468
- attemptId: ensuredOwnedTurn.attemptId,
469
- nativeTurnId: ensuredOwnedTurn.turnId
470
- }),
425
+ nativeSessionId: session.nativeSessionId,
426
+ conversationId: session.conversationId,
427
+ ...(restoredOwnedTurn === undefined
428
+ ? {}
429
+ : {
430
+ attemptId: restoredOwnedTurn.attemptId,
431
+ nativeTurnId: restoredOwnedTurn.turnId
432
+ }),
471
433
  ...authorityFields()
472
434
  }));
473
435
  return snapshot;
@@ -488,33 +450,21 @@ export async function runAgentHost(input) {
488
450
  conversationRecoverability = "unknown";
489
451
  authority = undefined;
490
452
  }
491
- const deliveryUnknown = error instanceof ProviderDeliveryUnknownError
492
- || providerAcceptedAttemptId !== undefined;
493
- const state = deliveryUnknown
494
- ? "delivery-unknown"
495
- : error instanceof ProviderTurnBusyError
496
- ? "busy"
497
- : error instanceof ProviderTurnRejectedError ? "rejected" : "failed";
453
+ const state = error instanceof ProviderTurnBusyError
454
+ ? "busy"
455
+ : error instanceof ProviderTurnRejectedError ? "rejected" : "failed";
498
456
  updateSnapshot(hostSnapshot(state, {
499
457
  launchId: next.launchId,
500
458
  adapterId: providerControl.adapterId,
501
459
  processInstanceId: session?.processInstanceId,
502
460
  nativeSessionId: session?.nativeSessionId ?? providerControl.nativeSessionId,
503
461
  conversationId: session?.conversationId ?? providerControl.nativeSessionId,
504
- ...(providerControl.initialTurn === undefined
505
- ? {}
506
- : { attemptId: providerControl.initialTurn.attemptId }),
507
462
  ...authorityFields(),
508
463
  detail: errorText(error)
509
464
  }));
510
- if (state !== "delivery-unknown") {
511
- activeTurnPayload = undefined;
512
- activeTurnAttemptId = undefined;
513
- activeNativeTurnId = undefined;
514
- }
515
- if (deliveryUnknown && !(error instanceof ProviderDeliveryUnknownError)) {
516
- throw new ProviderDeliveryUnknownError(`Provider accepted input but its durable acknowledgement could not be confirmed: ${errorText(error)}`, providerAcceptedAttemptId);
517
- }
465
+ activeTurnPayload = undefined;
466
+ activeTurnAttemptId = undefined;
467
+ activeNativeTurnId = undefined;
518
468
  throw error;
519
469
  }
520
470
  };
@@ -536,9 +486,15 @@ export async function runAgentHost(input) {
536
486
  throw new Error("Agent Host rejected a stale Provider writer fence.");
537
487
  }
538
488
  if (activeTurnPayload !== undefined || snapshot.state === "settling") {
539
- throw new Error("Agent Host still owns an unsettled Provider Turn.");
489
+ throw new ProviderTurnBusyError("Agent Host still owns an unsettled Provider Turn.", request.turn.attemptId, activeNativeTurnId);
540
490
  }
541
- activeTurnPayload = sessionPayload;
491
+ activeTurnPayload = {
492
+ ...sessionPayload,
493
+ environment: {
494
+ ...sessionPayload.environment,
495
+ YUI_RUN_ID: request.runId
496
+ }
497
+ };
542
498
  activeTurnAttemptId = request.turn.attemptId;
543
499
  activeNativeTurnId = undefined;
544
500
  updateSnapshot(hostSnapshot("starting", {
@@ -550,17 +506,26 @@ export async function runAgentHost(input) {
550
506
  attemptId: request.turn.attemptId,
551
507
  ...authorityFields()
552
508
  }));
509
+ const durableTurn = hostTurnControlParams(sessionPayload, session.nativeSessionId, request.authority, request.turn.attemptId, request.runId);
510
+ await beginDurableProviderTurn(input.home, durableTurn);
553
511
  let providerAccepted = false;
554
512
  try {
555
513
  const receipt = await session.submitTurn(request.turn);
556
514
  providerAccepted = true;
557
515
  activeNativeTurnId = receipt.nativeTurnId;
558
- await publishStructuredProviderAccepted({
559
- home: input.home,
560
- environment: sessionPayload.environment,
561
- activationId: activationId ?? sessionPayload.launchId,
562
- receipt
563
- });
516
+ try {
517
+ await publishStructuredProviderAccepted({
518
+ home: input.home,
519
+ environment: sessionPayload.environment,
520
+ activationId: activationId ?? sessionPayload.launchId,
521
+ receipt
522
+ });
523
+ }
524
+ catch (error) {
525
+ const unknown = new ProviderDeliveryUnknownError(`Provider accepted input but its durable acknowledgement could not be confirmed: ${errorText(error)}`, request.turn.attemptId);
526
+ await resolveProviderTurnSubmission(input.home, durableTurn, unknown);
527
+ throw unknown;
528
+ }
564
529
  updateSnapshot(hostSnapshot("ready", {
565
530
  launchId: request.launchId,
566
531
  adapterId: session.adapterId,
@@ -574,6 +539,9 @@ export async function runAgentHost(input) {
574
539
  return snapshot;
575
540
  }
576
541
  catch (error) {
542
+ if (!providerAccepted) {
543
+ await resolveProviderTurnSubmission(input.home, durableTurn, error);
544
+ }
577
545
  const deliveryUnknown = error instanceof ProviderDeliveryUnknownError || providerAccepted;
578
546
  const state = deliveryUnknown
579
547
  ? "delivery-unknown"
@@ -684,6 +652,7 @@ export async function runAgentHost(input) {
684
652
  type: "submit-turn",
685
653
  launchId: currentPayload.launchId,
686
654
  nativeSessionId: currentSession.nativeSessionId,
655
+ runId: requiredEnvironment(currentPayload.environment.YUI_RUN_ID, "Run id"),
687
656
  authority: currentAuthority,
688
657
  turn: {
689
658
  attemptId,
@@ -902,8 +871,10 @@ export async function openAgentHostControl(home, payload, snapshot, dispatch) {
902
871
  }
903
872
  catch (error) {
904
873
  const current = snapshot();
905
- socket.end(`${JSON.stringify(controlResult("rejected", validateSnapshot({
874
+ const busy = error instanceof ProviderTurnBusyError;
875
+ socket.end(`${JSON.stringify(controlResult(busy ? "accepted" : "rejected", validateSnapshot({
906
876
  ...current,
877
+ ...(busy ? { state: "busy" } : {}),
907
878
  detail: errorText(error),
908
879
  updatedAt: new Date().toISOString()
909
880
  })))}\n`);
@@ -951,6 +922,7 @@ function validateControl(control) {
951
922
  if (control.type === "submit-turn") {
952
923
  validateLaunchId(control.launchId);
953
924
  validateIdentity(control.nativeSessionId, "native Session id");
925
+ validateIdentity(control.runId, "Run id");
954
926
  validateProviderAuthorityFence(control.authority);
955
927
  validateIdentity(control.turn.attemptId, "Provider input attempt id");
956
928
  if (typeof control.turn.boundedText !== "string"
@@ -1056,12 +1028,12 @@ async function delay(milliseconds) {
1056
1028
  timer.unref();
1057
1029
  });
1058
1030
  }
1059
- function hostTurnControlParams(payload, nativeSessionId, authority, attemptId) {
1031
+ function hostTurnControlParams(payload, nativeSessionId, authority, attemptId, runId = requiredEnvironment(payload.environment.YUI_RUN_ID, "Run id")) {
1060
1032
  const environment = payload.environment;
1061
1033
  return Object.freeze({
1062
1034
  taskId: requiredEnvironment(environment.YUI_TASK_ID, "Task id"),
1063
1035
  roleName: requiredEnvironment(environment.YUI_ROLE, "Role name"),
1064
- runId: requiredEnvironment(environment.YUI_RUN_ID, "Run id"),
1036
+ runId: requiredEnvironment(runId, "Run id"),
1065
1037
  agentId: requiredEnvironment(environment.YUI_AGENT_ID, "Agent id"),
1066
1038
  launchId: payload.launchId,
1067
1039
  nativeSessionId: requiredEnvironment(nativeSessionId, "native Session id"),
@@ -1120,6 +1092,7 @@ async function resolveProviderTurnSubmission(home, durableTurn, error) {
1120
1092
  ? "delivery-unknown"
1121
1093
  : "rejected",
1122
1094
  reason: errorText(error),
1095
+ raw: serializeAgentErrorRaw(error),
1123
1096
  observedAt: new Date().toISOString()
1124
1097
  };
1125
1098
  try {
@@ -1,6 +1,7 @@
1
1
  import { AgentDriverRegistry } from "./agentDriver.js";
2
2
  import { claudeTranscriptObserver, codexTranscriptObserver, transcriptObserverSource } from "./builtinTranscriptObserver.js";
3
- import { parseClaudeError } from "./providerErrorCodes.js";
3
+ import { mapClaudeAgentError, mapCodexAgentError } from "./builtinAgentErrorMappers.js";
4
+ import { serializeAgentErrorRaw, standardAgentError } from "./agentError.js";
4
5
  export const CODEX_DRIVER_ID = "openai/codex";
5
6
  export const CLAUDE_CODE_DRIVER_ID = "anthropic/claude-code";
6
7
  export function builtinDriverIdForAdapter(adapterId) {
@@ -77,6 +78,7 @@ export const BUILTIN_AGENT_DRIVERS = Object.freeze([
77
78
  runtime: Object.freeze({
78
79
  nativeSessionId: ({ payload }) => (optionalIdentityFrom(payload, ["session_id"])),
79
80
  nativeTurnId: ({ payload }) => (optionalIdentityFrom(payload, ["prompt_id", "turn_id"])),
81
+ mapError: mapClaudeAgentError,
80
82
  mapHook: ({ hookEventName, payload, occurrenceId }) => (mapClaudeHook(hookEventName, payload, occurrenceId)),
81
83
  classifyHook: ({ hookEventName, payload }) => Object.freeze({
82
84
  ...(hookEventName === "SessionStart" && payload.source === "startup"
@@ -133,6 +135,7 @@ export const BUILTIN_AGENT_DRIVERS = Object.freeze([
133
135
  runtime: Object.freeze({
134
136
  nativeSessionId: ({ payload }) => (optionalIdentityFrom(payload, ["session_id"])),
135
137
  nativeTurnId: ({ payload }) => (optionalIdentityFrom(payload, ["turn_id", "prompt_id"])),
138
+ mapError: mapCodexAgentError,
136
139
  mapHook: ({ hookEventName, payload, occurrenceId }) => (mapCodexHook(hookEventName, payload, occurrenceId)),
137
140
  classifyHook: ({ hookEventName, payload }) => Object.freeze({
138
141
  ...(hookEventName === "SessionStart"
@@ -237,7 +240,10 @@ function mapClaudeHook(name, payload, occurrenceId) {
237
240
  case "StopFailure":
238
241
  return mapped("turn.failed", claudeFailure(payload));
239
242
  case "SessionEnd":
240
- return [mapped("session.ended"), mapped("activation.ended")];
243
+ // Native CLI exit ends this local Provider attachment, not the
244
+ // resumable Conversation. Durable Session end is an explicit Yui
245
+ // mutation or a Provider fact that the Conversation is unrecoverable.
246
+ return mapped("activation.ended");
241
247
  default:
242
248
  throw new Error(`Claude Code Driver does not support Hook event: ${name}.`);
243
249
  }
@@ -291,7 +297,7 @@ function mapCodexHook(name, payload, occurrenceId) {
291
297
  case "Stop":
292
298
  return mapped("turn.completed", optionalSummary(payload));
293
299
  case "SessionEnd":
294
- return [mapped("session.ended"), mapped("activation.ended")];
300
+ return mapped("activation.ended");
295
301
  default:
296
302
  throw new Error(`Codex Driver does not support Hook event: ${name}.`);
297
303
  }
@@ -376,7 +382,8 @@ function claudeFailure(payload) {
376
382
  const code = firstIdentity(payload, ["error"], "Claude StopFailure error");
377
383
  const details = optionalText(payload.error_details);
378
384
  const lastOutput = optionalText(payload.last_assistant_message);
379
- const parsed = parseClaudeError(code, details);
385
+ const raw = serializeAgentErrorRaw(payload);
386
+ const classification = mapClaudeAgentError({ message: code, raw });
380
387
  const retryAfterMs = typeof payload.retry_after_ms === "number"
381
388
  && Number.isSafeInteger(payload.retry_after_ms)
382
389
  && payload.retry_after_ms > 0
@@ -384,14 +391,19 @@ function claudeFailure(payload) {
384
391
  : undefined;
385
392
  return {
386
393
  failure: {
387
- ...(parsed.code !== "unknown" ? { errorCode: parsed.code } : {}),
388
- code,
389
- ...(details === undefined ? {} : { details }),
394
+ error: standardAgentError({
395
+ source: "provider",
396
+ phase: "turn-execute",
397
+ classification,
398
+ message: code,
399
+ raw,
400
+ inputDisposition: "accepted",
401
+ ...(retryAfterMs === undefined ? {} : { retryAfterMs })
402
+ }),
390
403
  ...(lastOutput === undefined ? {} : { lastOutput }),
391
404
  ...(payload.run_terminal === true || payload.unrecoverable === true
392
405
  ? { runTerminal: true }
393
- : {}),
394
- ...(retryAfterMs === undefined ? {} : { retryAfterMs })
406
+ : {})
395
407
  },
396
408
  summary: [
397
409
  "Agent turn failed.",