@zq-silk/yui 0.13.9 → 0.14.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 (229) hide show
  1. package/ARCHITECTURE.md +69 -428
  2. package/README.md +108 -298
  3. package/dist/agent/managedRuntimeEnvironment.js +2 -2
  4. package/dist/cli/commandCatalog.js +39 -77
  5. package/dist/cli/interactionCandidates.js +4 -4
  6. package/dist/cli/interactionPolicy.js +7 -10
  7. package/dist/cli/invocationRouter.js +1 -1
  8. package/dist/cli/updateCommand.js +6 -27
  9. package/dist/cli/updateOrchestrator.js +63 -484
  10. package/dist/cli/updatePorts.js +15 -333
  11. package/dist/cli/upgradeCommand.js +8 -65
  12. package/dist/cli.js +57 -242
  13. package/dist/commands/configCommands.js +11 -62
  14. package/dist/commands/executionAuditCommands.js +23 -23
  15. package/dist/commands/globalRoleCommands.js +2 -7
  16. package/dist/commands/jobCommands.js +1 -4
  17. package/dist/commands/projectCommands.js +5 -5
  18. package/dist/commands/releaseCommands.js +3 -10
  19. package/dist/commands/resourcesCommands.js +2 -2
  20. package/dist/commands/sessionCommands.js +2 -2
  21. package/dist/commands/taskActor.js +31 -39
  22. package/dist/commands/taskChangeSetCommands.js +5 -12
  23. package/dist/commands/taskCommands.js +464 -1249
  24. package/dist/commands/taskContextCommand.js +35 -36
  25. package/dist/commands/taskExecutionCommands.js +33 -46
  26. package/dist/commands/taskInputCommands.js +20 -42
  27. package/dist/commands/taskNextActionCommand.js +9 -9
  28. package/dist/commands/taskOverviewCommand.js +56 -95
  29. package/dist/commands/taskRoleRuntimeStatus.js +77 -107
  30. package/dist/commands/taskUpstreamCommands.js +3 -3
  31. package/dist/commands/taskWorkspaceCommands.js +7 -79
  32. package/dist/commands/telemetryCommands.js +32 -124
  33. package/dist/commands/workflowCommands.js +3 -3
  34. package/dist/completion/fileCompletionManager.js +1 -1
  35. package/dist/config/configCatalog.js +4 -6
  36. package/dist/config/yuiConfig.js +6 -43
  37. package/dist/context/dispatchContext.js +14 -30
  38. package/dist/context/roleSessionContext.js +2 -2
  39. package/dist/context/sessionBootstrapManifest.js +2 -2
  40. package/dist/context/{runContextPack.js → turnContextPack.js} +58 -73
  41. package/dist/context/turnInputContract.js +204 -0
  42. package/dist/context/wakeNotification.js +2 -2
  43. package/dist/controller/agentRuntimeObserver.js +18 -18
  44. package/dist/controller/clientRuntime.js +13 -20
  45. package/dist/controller/controller.js +89 -116
  46. package/dist/controller/fileSchedulerStoreAdapter.js +511 -742
  47. package/dist/controller/jobControl.js +17 -17
  48. package/dist/controller/resourceInventory.js +6 -6
  49. package/dist/controller/resourceInventoryLinux.js +38 -59
  50. package/dist/controller/resourceInventoryRpc.js +3 -3
  51. package/dist/controller/resourceInventoryWorker.js +1 -1
  52. package/dist/controller/runtime.js +46 -53
  53. package/dist/controller/runtimeEventInbox.js +23 -31
  54. package/dist/controller/runtimeEventProcessor.js +15 -15
  55. package/dist/controller/{runtimeHookRunFence.js → runtimeHookTurnFence.js} +87 -81
  56. package/dist/controller/runtimeLaunchCoordinator.js +3 -3
  57. package/dist/controller/runtimeObservationHook.js +11 -8
  58. package/dist/controller/sessionNotify.js +11 -11
  59. package/dist/controller/structuredProviderObservation.js +89 -16
  60. package/dist/coordination/workMailbox.js +309 -579
  61. package/dist/coordination/workMailboxQueue.js +5 -6
  62. package/dist/core/controllerClient.js +1 -91
  63. package/dist/core/controllerServer.js +3 -6
  64. package/dist/doctor/doctor.js +51 -314
  65. package/dist/execution/candidateConvergence.js +3 -3
  66. package/dist/execution/executionGroup.js +32 -33
  67. package/dist/execution/executionHealth.js +36 -38
  68. package/dist/execution/resourceBroker.js +12 -12
  69. package/dist/executor/agentExecutor.js +30 -265
  70. package/dist/executor/effectiveLaunch.js +9 -19
  71. package/dist/executor/executorRegistry.js +43 -17
  72. package/dist/executor/fileRoleLaunchPlanner.js +56 -56
  73. package/dist/executor/launchPlan.js +3 -3
  74. package/dist/executor/workspacePreflightClassification.js +16 -16
  75. package/dist/grant/capabilityGrant.js +20 -25
  76. package/dist/input/inputRequest.js +12 -12
  77. package/dist/integration/changeSet.js +9 -13
  78. package/dist/integration/changeSetManifest.js +1 -1
  79. package/dist/integration/gitIntegrationService.js +2 -2
  80. package/dist/integration/integrationQueueService.js +5 -21
  81. package/dist/integration/overlapDiagnostics.js +2 -2
  82. package/dist/interaction/operatorPresentation.js +1 -1
  83. package/dist/job/jobRunner.js +1 -1
  84. package/dist/lifecycle/canonicalLifecycleEvent.js +25 -25
  85. package/dist/lifecycle/{exactRunTerminalization.js → exactTurnTerminalization.js} +116 -232
  86. package/dist/message/message.js +6 -6
  87. package/dist/observability/executionAudit.js +74 -86
  88. package/dist/observability/faultClassification.js +7 -24
  89. package/dist/observability/orchestrationMetrics.js +5 -5
  90. package/dist/observability/runtimeIdentity.js +34 -101
  91. package/dist/profile/agentProfile.js +1 -1
  92. package/dist/release/cliHomeReleaseFence.js +3 -3
  93. package/dist/release/releaseWorkflowEngine.js +6 -10
  94. package/dist/release/releaseWorkflowPorts.js +2 -2
  95. package/dist/release/workflowFileLock.js +1 -1
  96. package/dist/repository/checkoutSwap.js +1 -1
  97. package/dist/repository/gitWorkspace.js +0 -13
  98. package/dist/repository/project.js +1 -1
  99. package/dist/repository/projectMaintenanceLock.js +1 -2
  100. package/dist/repository/taskBaseFreshness.js +13 -13
  101. package/dist/repository/taskWorkspaceCoordinator.js +21 -25
  102. package/dist/repository/taskWorkspaceIdentity.js +8 -21
  103. package/dist/repository/taskWorkspacePreparer.js +63 -620
  104. package/dist/resources/autoResourceGc.js +3 -3
  105. package/dist/resources/liveReferences.js +1 -1
  106. package/dist/resources/resourceGc.js +1 -1
  107. package/dist/resources/sqliteResourceRegistry.js +1 -1
  108. package/dist/review/reviewDecision.js +7 -7
  109. package/dist/review/reviewFindingLedger.js +1 -1
  110. package/dist/review/reviewOutcomeClassifier.js +35 -50
  111. package/dist/review/reviewRound.js +14 -25
  112. package/dist/review/reviewerAvailability.js +4 -4
  113. package/dist/review/taskFinalReviewContractResolution.js +41 -0
  114. package/dist/role/role.js +6 -3
  115. package/dist/runtime/agentDriver.js +4 -0
  116. package/dist/runtime/agentHost.js +151 -36
  117. package/dist/runtime/builtinAgentDrivers.js +79 -2
  118. package/dist/runtime/codexAppServerRuntime.js +122 -0
  119. package/dist/runtime/continuationManager.js +3 -5
  120. package/dist/runtime/exactControlPlane.js +17 -42
  121. package/dist/runtime/firstProgressAdvisory.js +1 -1
  122. package/dist/runtime/index.js +2 -2
  123. package/dist/runtime/launchDiagnostics.js +2 -2
  124. package/dist/runtime/lifecycleReservation.js +4 -4
  125. package/dist/runtime/processExitObservation.js +1 -1
  126. package/dist/runtime/processExitOutbox.js +0 -32
  127. package/dist/runtime/promptEnvelope.js +9 -9
  128. package/dist/runtime/providerContinuation.js +2 -2
  129. package/dist/runtime/providerContinuationReconciliationService.js +2 -2
  130. package/dist/runtime/providerRuntimeIdentity.js +76 -24
  131. package/dist/runtime/recentTurnIds.js +38 -0
  132. package/dist/runtime/runtimeContinuationProjection.js +2 -2
  133. package/dist/runtime/runtimeHealthPolicy.js +1 -1
  134. package/dist/runtime/runtimeObservation.js +58 -21
  135. package/dist/runtime/runtimeProjection.js +19 -27
  136. package/dist/runtime/sessionLaunchRequest.js +2 -2
  137. package/dist/runtime/structuredProviderHost.js +177 -12
  138. package/dist/runtime/tmuxAdapters.js +46 -11
  139. package/dist/scheduler/activeRoleTurnDelivery.js +245 -0
  140. package/dist/scheduler/leaderWakeupProcessor.js +147 -445
  141. package/dist/scheduler/operatorEvent.js +4 -6
  142. package/dist/scheduler/resourceQueueProjection.js +71 -0
  143. package/dist/scheduler/{roleRunLiveness.js → roleTurnLiveness.js} +24 -28
  144. package/dist/scheduler/{roleRunStall.js → roleTurnStall.js} +162 -247
  145. package/dist/scheduler/taskExecutionProjection.js +99 -99
  146. package/dist/scheduler/taskObservabilityProjection.js +10 -10
  147. package/dist/scheduler/taskWake.js +4 -4
  148. package/dist/scheduler/wakeReason.js +6 -10
  149. package/dist/scheduler/wakeupQueue.js +0 -9
  150. package/dist/setup/setupCommand.js +2 -2
  151. package/dist/storage/currentTaskStore.js +46 -0
  152. package/dist/storage/persistenceWorker.js +1 -1
  153. package/dist/storage/sqliteSchema.js +81 -485
  154. package/dist/storage/sqliteStore.js +206 -365
  155. package/dist/storage/storageSchema.js +1 -15
  156. package/dist/storage/storageVersions.js +8 -9
  157. package/dist/storage/storeRpc.js +10 -34
  158. package/dist/storage/taskStore.js +63 -3415
  159. package/dist/storage/upgrade/recordVersions.js +55 -149
  160. package/dist/storage/upgrade/upgradeOrchestrator.js +89 -1752
  161. package/dist/task/completionReadiness.js +5 -5
  162. package/dist/task/deliveryGuard.js +10 -10
  163. package/dist/task/nextAction.js +74 -77
  164. package/dist/task/task.js +2 -4
  165. package/dist/task/taskRecordReference.js +3 -3
  166. package/dist/task/taskRecordRetirement.js +1 -1
  167. package/dist/telemetry/sqliteTelemetryStore.js +53 -53
  168. package/dist/telemetry/telemetryConfig.js +14 -14
  169. package/dist/telemetry/telemetryWiring.js +8 -14
  170. package/dist/turn/turn.js +356 -0
  171. package/dist/{run/runIdentity.js → turn/turnIdentity.js} +4 -4
  172. package/dist/verification/gateArtifactStore.js +2 -2
  173. package/dist/web/assets/client/app.js +1 -1
  174. package/dist/web/assets/client/components.js +29 -54
  175. package/dist/web/assets/client/i18n.js +17 -37
  176. package/dist/web/assets/client/view.js +37 -37
  177. package/dist/web/assets/shell.js +1 -1
  178. package/dist/web/assets/styles/cards.js +5 -5
  179. package/dist/web/assets/styles/widgets.js +1 -2
  180. package/dist/web/webSnapshot.js +65 -60
  181. package/dist/workItem/workItem.js +11 -11
  182. package/dist/workspace/workItemChangeSetManager.js +1 -1
  183. package/docs/task-local-identity.md +5 -5
  184. package/i18n/README.zh-CN.md +41 -54
  185. package/package.json +1 -1
  186. package/skills/yui-leader/SKILL.md +85 -83
  187. package/skills/yui-operator/SKILL.md +16 -16
  188. package/skills/yui-reviewer/SKILL.md +10 -10
  189. package/skills/yui-runtime/SKILL.md +17 -18
  190. package/skills/yui-worker/SKILL.md +16 -18
  191. package/dist/context/runContextContract.js +0 -162
  192. package/dist/executor/turnCompletion.js +0 -126
  193. package/dist/review/taskFinalReviewContractEvent.js +0 -1
  194. package/dist/review/taskFinalReviewContractRebind.js +0 -367
  195. package/dist/run/agentRun.js +0 -356
  196. package/dist/run/rejectedYieldAttempt.js +0 -221
  197. package/dist/run/runControlRequest.js +0 -50
  198. package/dist/run/yieldReceipt.js +0 -65
  199. package/dist/runtime/turnCompletion.js +0 -3
  200. package/dist/scheduler/actionability.js +0 -323
  201. package/dist/scheduler/activeRoleRunDelivery.js +0 -868
  202. package/dist/scheduler/activeTaskProgress.js +0 -126
  203. package/dist/storage/compatibleTaskStore.js +0 -248
  204. package/dist/storage/migration/baseline.js +0 -78
  205. package/dist/storage/migration/classifier.js +0 -51
  206. package/dist/storage/migration/compatibleCodec.js +0 -53
  207. package/dist/storage/migration/engine.js +0 -147
  208. package/dist/storage/migration/index.js +0 -33
  209. package/dist/storage/migration/planner.js +0 -154
  210. package/dist/storage/migration/productionRegistry.js +0 -3931
  211. package/dist/storage/migration/registry.js +0 -169
  212. package/dist/storage/migration/report.js +0 -54
  213. package/dist/storage/migration/types.js +0 -31
  214. package/dist/storage/upgrade/homeClassification.js +0 -353
  215. package/dist/storage/upgrade/homeMigrationTarget.js +0 -595
  216. package/dist/storage/upgrade/migrationReceipt.js +0 -67
  217. package/dist/storage/upgrade/offlineUpgradeInventory.js +0 -453
  218. package/dist/storage/upgrade/productionMigrationRegistry.js +0 -6
  219. package/dist/storage/upgrade/pseudoLayoutRepair.js +0 -241
  220. package/dist/storage/upgrade/recordVersionScan.js +0 -176
  221. package/dist/storage/upgrade/sqliteFileSet.js +0 -50
  222. package/dist/storage/upgrade/sqliteMigrationTarget.js +0 -375
  223. package/dist/storage/upgrade/sqliteRecordMigrationTarget.js +0 -305
  224. package/dist/storage/upgrade/sqliteStateMigration.js +0 -918
  225. package/dist/storage/upgrade/switchProgress.js +0 -80
  226. package/dist/storage/upgrade/upgradeReceipt.js +0 -161
  227. package/dist/storage/upgradeCoordination.js +0 -187
  228. package/dist/storage/upgradeFence.js +0 -366
  229. package/dist/telemetry/telemetryCompaction.js +0 -252
@@ -1,25 +1,25 @@
1
1
  ---
2
2
  name: yui-runtime
3
- description: Load and use the authorized context for every Yui-managed Leader, Worker, Reviewer, Operator, or custom Role Run, and complete that Run through its bounded control-plane protocol.
3
+ description: Load and use the authorized context for every Yui-managed Leader, Worker, Reviewer, Operator, or custom Role Turn, and complete that Turn through its bounded control-plane protocol.
4
4
  ---
5
5
 
6
6
  # Yui Runtime
7
7
 
8
- Treat the Session Manifest and Run Bootstrap Envelope as pointers, never as the
8
+ Treat the Session Manifest and Turn Bootstrap Envelope as pointers, never as the
9
9
  Task brief. Do not infer Task facts from the launch command, process list,
10
- workspace layout, native transcript, or an earlier Run.
10
+ workspace layout, native transcript, or an earlier Turn.
11
11
 
12
- For every managed Task Run:
12
+ For every managed Task Turn:
13
13
 
14
- 1. Read the exact Run identity from the newest Bootstrap Envelope.
14
+ 1. Read the exact Turn identity from the newest Bootstrap Envelope.
15
15
  2. Before acting, load its authorized pack with the Session CLI named by the
16
16
  current Session Manifest:
17
17
 
18
18
  ```sh
19
- "$YUI_SESSION_CLI" task run context "$YUI_TASK_ID/<run-id>" --json
19
+ "$YUI_SESSION_CLI" task turn context "$YUI_TASK_ID/<turn-id>" --json
20
20
  ```
21
21
 
22
- 3. Verify that the returned Task, Run, Role, purpose, Snapshot digest, workspace,
22
+ 3. Verify that the returned Task, Turn, Role, purpose, Snapshot digest, workspace,
23
23
  and Adapter match the Envelope and Session Manifest. Stop and report a
24
24
  context-load failure if the pack is missing, stale, unauthorized, malformed,
25
25
  or mismatched. Never request an inline/full-prompt fallback.
@@ -28,7 +28,7 @@ For every managed Task Run:
28
28
  `refId`:
29
29
 
30
30
  ```sh
31
- "$YUI_SESSION_CLI" task run context expand "$YUI_TASK_ID/<run-id>" <ref-id> --store <store> --mode full --json
31
+ "$YUI_SESSION_CLI" task turn context expand "$YUI_TASK_ID/<turn-id>" <ref-id> --store <store> --mode full --json
32
32
  ```
33
33
 
34
34
  A bare `<ref-id>` remains supported only when it identifies exactly one
@@ -40,8 +40,8 @@ For every managed Task Run:
40
40
  from transcript memory.
41
41
 
42
42
  The pack's authority view and writable Project IDs are hard boundaries. A
43
- native subagent inherits the parent Run's refs and authority; it does not gain a
44
- new Yui actor, Run, Session, or cross-Task read permission.
43
+ native subagent inherits the parent Turn's refs and authority; it does not gain a
44
+ new Yui actor, Turn, Session, or cross-Task read permission.
45
45
 
46
46
  For a global Operator or custom GlobalRole Session, load the stable authorized view
47
47
  before routing or acting:
@@ -52,18 +52,17 @@ before routing or acting:
52
52
 
53
53
  Global context grants no Task implementation workspace. Read a Task only after
54
54
  the Operator has routed to its public/task-authorized context command; never
55
- invent a Task Run identity for a GlobalRole.
55
+ invent a Task Turn identity for a GlobalRole.
56
56
 
57
- Provider acceptance, Context load, and workflow completion are separate facts.
58
- Do not treat a live pane, process output, final response, or completed Provider
59
- Turn as a Yui yield. For a managed Task Run, use the exact current Run's
60
- supported checkpoint/yield command as the final control-plane action, then stop
61
- immediately. If that direct command is denied or stale, report the blocker once
62
- and stop; do not wrap, retry, broaden permissions, or target another Run.
57
+ Provider acceptance, Context load, Turn completion, and Task completion are
58
+ separate facts. For a managed Task Turn, end the Provider Turn with one truthful
59
+ final report. Yui automatically correlates that native terminal with the exact
60
+ current Turn and persists the report; no completion command is required. The
61
+ Leader alone decides whether the WorkItem or Task is complete.
63
62
 
64
63
  After a failed Provider Turn, read the referenced `runtime.agent-error` fact.
65
64
  The failed Turn is immutable; a recovery is always a new Turn. Continue on the
66
- same native Session when it remains recoverable, and load only the current Run
65
+ same native Session when it remains recoverable, and load only the current Turn
67
66
  delta instead of replaying its original Assignment. A new Host process does not
68
67
  imply a new Session, and a new Session must never be substituted silently for
69
68
  the persisted native Session id.
@@ -1,18 +1,18 @@
1
1
  ---
2
2
  name: yui-worker
3
- description: Complete one bounded WorkItem as a native subagent or Task Role AgentRun, then return honest evidence through the assigned protocol.
3
+ description: Complete one bounded WorkItem as a native subagent or Task Role Turn, then return honest evidence through the assigned protocol.
4
4
  ---
5
5
 
6
6
  # Yui Worker
7
7
 
8
- Follow `yui-runtime` first. For a managed Run, load its exact Context Pack and
8
+ Follow `yui-runtime` first. For a managed Turn, load its exact Context Pack and
9
9
  use only the returned WorkItem, refs, workspace, writable Project IDs, and
10
10
  completion actions. The launch Envelope is a pointer, not an execution brief.
11
11
 
12
12
  Complete only the assigned substantial, independently owned WorkItem. The Leader owns Task direction,
13
13
  decomposition, acceptance, integration, scope expansion, and conflict
14
14
  decisions. A Worker must not create or rebind Yui worktrees, Sessions, Roles,
15
- Runs, WorkItems, ReviewRounds, or integration state.
15
+ Turns, WorkItems, ReviewRounds, or integration state.
16
16
 
17
17
  Keep the layers distinct:
18
18
 
@@ -21,7 +21,7 @@ Keep the layers distinct:
21
21
  - This Skill supplies portable Worker behavior.
22
22
  - Agent-native Project Skills plus Project Policy and Knowledge supply build,
23
23
  test, migration, release, and review rules.
24
- - The exact WorkItem and Context Snapshot supply this Run's objective, scope,
24
+ - The exact WorkItem and Context Snapshot supply this Turn's objective, scope,
25
25
  acceptance, dependencies, and evidence contract.
26
26
 
27
27
  Do not promote a Project convention into generic Worker policy or infer Task
@@ -30,8 +30,8 @@ pack.
30
30
 
31
31
  ## Execute within the exact boundary
32
32
 
33
- - Preserve the Task, WorkItem, Role, Run, native Session, and workspace
34
- identities supplied by Yui. A new Run is another attempt or continuation of
33
+ - Preserve the Task, WorkItem, Role, Turn, native Session, and workspace
34
+ identities supplied by Yui. A new Turn is another attempt or continuation of
35
35
  the same delivery unit; do not request a fresh Role or Session merely because
36
36
  implementation entered another step or repair round.
37
37
  - Follow the configured Profile's responsibilities, constraints, access
@@ -76,27 +76,25 @@ the Leader consumes it, the child may need to rerun. Do not claim Yui
76
76
  durability for a native result you only emitted in the provider transcript.
77
77
  When the child brief requires a durable, independently recoverable result,
78
78
  the Leader must dispatch the work as a Yui WorkItem/ExecutionGroup instead —
79
- native subagents never own a Yui Run, receipt, or workspace.
79
+ native subagents never own a Yui Turn, receipt, or workspace.
80
80
 
81
- ## Task Role AgentRun
81
+ ## Task Role Turn
82
82
 
83
83
  Summarize the outcome for the Leader's next judgment, not as a transcript or
84
84
  file-by-file log. Include the observable result, important mechanism and
85
85
  boundary, changed paths and commit state, checks, skipped validation, blockers,
86
86
  residual risk, and bounded next action. Use a checkpoint only for material
87
- semantic progress during a long Run; it does not replace the final handoff.
87
+ semantic progress during a long Turn; it does not replace the final handoff.
88
88
 
89
89
  For a native subagent, return one consolidated child result through the native
90
90
  child-result mechanism. Do not run Yui lifecycle commands or invent a child
91
- Yui Session/Run.
92
-
93
- For a managed Task Role, use only the exact completion action returned by the
94
- Run Context Pack and follow `yui-runtime`'s direct-once/final-action rule. An
95
- execution yield creates immutable Candidate evidence but does not accept,
96
- capture, integrate, or complete the WorkItem. A review yield creates review
97
- evidence only; the Leader decides disposition. If the exact handoff is denied,
98
- stale, or mismatched, report that blocker once and stop without wrappers,
99
- permission broadening, or another Run target.
91
+ Yui Session/Turn.
92
+
93
+ For a managed Task Role, end the Provider Turn with one complete, truthful
94
+ result. Yui persists it automatically on the exact Turn. That result does not
95
+ accept, capture, integrate, or complete the WorkItem; the Leader decides its
96
+ disposition. If context or scope is stale or mismatched, report that blocker
97
+ once and stop without wrappers, permission broadening, or another Turn target.
100
98
 
101
99
  Leave managed workspaces intact after handoff. Their owner lifecycle and
102
100
  cleanup belong to the Leader and Yui Core.
@@ -1,162 +0,0 @@
1
- import { normalizedUniqueIdentities, requireIdentity, requireText } from "../domain/validation.js";
2
- import { validateContextSnapshotRef } from "./contextSnapshot.js";
3
- export const RUN_CONTEXT_PROTOCOL_VERSION = 1;
4
- export const RUN_BOOTSTRAP_PROTOCOL = "yui-run/v1";
5
- export const RUN_BOOTSTRAP_MAX_BYTES = 4 * 1024;
6
- export const RUN_BOOTSTRAP_MAX_DELTAS = 16;
7
- export const RUN_ACTIONS = [
8
- "lead-task",
9
- "leader-wake",
10
- "execute-work-item",
11
- "repair-work-item",
12
- "review-round",
13
- "review-delta",
14
- "global-request"
15
- ];
16
- export function createRunAssignment(input) {
17
- const common = normalizeCommon(input);
18
- return Object.freeze({
19
- schemaVersion: RUN_CONTEXT_PROTOCOL_VERSION,
20
- ...common,
21
- ...(input.directive === undefined
22
- ? {}
23
- : { directive: requireText(input.directive, "Run assignment directive") })
24
- });
25
- }
26
- export function validateRunAssignment(value) {
27
- if (value.schemaVersion !== RUN_CONTEXT_PROTOCOL_VERSION) {
28
- throw new Error("Run assignment must use schemaVersion 1.");
29
- }
30
- const normalized = createRunAssignment(value);
31
- if (JSON.stringify(normalized) !== JSON.stringify(value)) {
32
- throw new Error("Run assignment is not canonical.");
33
- }
34
- return value;
35
- }
36
- export function createRunBootstrapEnvelope(assignment) {
37
- validateRunAssignment(assignment);
38
- return Object.freeze({
39
- protocol: RUN_BOOTSTRAP_PROTOCOL,
40
- runId: assignment.runId,
41
- roleName: assignment.roleName,
42
- purpose: assignment.purpose,
43
- action: assignment.action,
44
- subject: assignment.subject,
45
- ...(assignment.contextSnapshotRef === undefined
46
- ? {}
47
- : { contextSnapshotRef: assignment.contextSnapshotRef }),
48
- deltaRefIds: assignment.deltaRefIds
49
- });
50
- }
51
- export function validateRunBootstrapEnvelope(value) {
52
- if (value.protocol !== RUN_BOOTSTRAP_PROTOCOL) {
53
- throw new Error("Run bootstrap protocol is unsupported.");
54
- }
55
- normalizeCommon(value);
56
- const serialized = serializeRunBootstrapEnvelope(value);
57
- if (Buffer.byteLength(serialized, "utf8") > RUN_BOOTSTRAP_MAX_BYTES) {
58
- throw new Error("Run bootstrap envelope exceeds its protocol byte limit.");
59
- }
60
- return value;
61
- }
62
- export function serializeRunBootstrapEnvelope(value) {
63
- if (value.protocol !== RUN_BOOTSTRAP_PROTOCOL) {
64
- throw new Error("Run bootstrap protocol is unsupported.");
65
- }
66
- const normalized = normalizeCommon(value);
67
- const subject = Object.entries(normalized.subject)
68
- .map(([key, id]) => `${key}:${id}`)
69
- .join(",");
70
- const snapshot = normalized.contextSnapshotRef;
71
- const lines = [
72
- "Yui managed Run. Follow the Session Manifest and injected Skills.",
73
- `${normalized.subject.taskId === undefined ? "" : `task=${normalized.subject.taskId} `}run=${normalized.runId} role=${normalized.roleName} action=${normalized.action}`,
74
- `purpose=${normalized.purpose} subject=${subject || "global"} snapshot=${snapshot === undefined ? "none" : `${snapshot.id}@${snapshot.digest}`}`,
75
- normalized.deltaRefIds.length === 0
76
- ? "delta=none"
77
- : `delta=${normalized.deltaRefIds.join(",")}`,
78
- "Load the exact Run context before acting; fail closed if it is unavailable or mismatched."
79
- ];
80
- const serialized = lines.join("\n");
81
- if (Buffer.byteLength(serialized, "utf8") > RUN_BOOTSTRAP_MAX_BYTES) {
82
- throw new Error("Run bootstrap envelope exceeds its protocol byte limit.");
83
- }
84
- return serialized;
85
- }
86
- /**
87
- * Bounded infrastructure-recovery input for an already-pushed Run. It resumes
88
- * the provider-native transcript after Host/child replacement and never
89
- * replays the Assignment or its directive.
90
- */
91
- export function serializeRunHostRecoveryEnvelope(value) {
92
- const normalized = normalizeCommon(value);
93
- const serialized = [
94
- "Yui managed Host recovery for an existing Run.",
95
- `${normalized.subject.taskId === undefined ? "" : `task=${normalized.subject.taskId} `}run=${normalized.runId} role=${normalized.roleName}`,
96
- "Resume the same native conversation from its latest durable state. Do not repeat completed work or replay the original Assignment.",
97
- "Load the exact Run context or delta only if needed, then continue toward the existing workflow outcome."
98
- ].join("\n");
99
- if (Buffer.byteLength(serialized, "utf8") > RUN_BOOTSTRAP_MAX_BYTES) {
100
- throw new Error("Run Host recovery envelope exceeds its protocol byte limit.");
101
- }
102
- return serialized;
103
- }
104
- function normalizeCommon(input) {
105
- if (!["execution", "review", "global"].includes(input.purpose)) {
106
- throw new Error("Run assignment purpose is invalid.");
107
- }
108
- if (!RUN_ACTIONS.includes(input.action)) {
109
- throw new Error("Run assignment action is invalid.");
110
- }
111
- const subject = normalizeSubject(input.subject);
112
- const snapshot = input.contextSnapshotRef === undefined
113
- ? undefined
114
- : validateContextSnapshotRef(input.contextSnapshotRef);
115
- if (snapshot !== undefined && snapshot.taskId !== subject.taskId) {
116
- throw new Error("Run assignment Context Snapshot belongs to another Task.");
117
- }
118
- if (input.purpose !== "global" && subject.taskId === undefined) {
119
- throw new Error("A Task Run assignment requires a Task subject.");
120
- }
121
- if (input.purpose === "review" && subject.reviewRoundId === undefined) {
122
- throw new Error("A review Run assignment requires a ReviewRound subject.");
123
- }
124
- const deltaRefIds = normalizedUniqueIdentities(input.deltaRefIds, "Run assignment delta ref");
125
- if (deltaRefIds.length > RUN_BOOTSTRAP_MAX_DELTAS) {
126
- throw new Error(`Run assignment supports at most ${RUN_BOOTSTRAP_MAX_DELTAS} delta refs.`);
127
- }
128
- return {
129
- runId: requireIdentity(input.runId, "Run assignment Run id"),
130
- roleName: requireIdentity(input.roleName, "Run assignment Role name"),
131
- purpose: input.purpose,
132
- action: input.action,
133
- subject,
134
- ...(snapshot === undefined ? {} : { contextSnapshotRef: snapshot }),
135
- deltaRefIds
136
- };
137
- }
138
- function normalizeSubject(subject) {
139
- const normalized = Object.fromEntries(Object.entries(subject).map(([key, value]) => [
140
- key,
141
- requireIdentity(value, `Run assignment ${key}`)
142
- ]));
143
- const allowed = [
144
- "taskId",
145
- "workItemId",
146
- "reviewRoundId",
147
- "executionGroupId",
148
- "executionLaneId"
149
- ];
150
- if (Object.keys(normalized).some((key) => !allowed.includes(key))) {
151
- throw new Error("Run assignment subject contains an unknown field.");
152
- }
153
- if ((normalized.executionGroupId === undefined) !== (normalized.executionLaneId === undefined)) {
154
- throw new Error("Run assignment execution lineage is incomplete.");
155
- }
156
- if (normalized.taskId === undefined
157
- && (normalized.workItemId !== undefined || normalized.reviewRoundId !== undefined
158
- || normalized.executionGroupId !== undefined)) {
159
- throw new Error("Run assignment child subject requires a Task id.");
160
- }
161
- return Object.freeze(normalized);
162
- }
@@ -1,126 +0,0 @@
1
- import { requireSafeIdentity, requireText, requireTimestamp } from "../runtime/validation.js";
2
- export const DEFAULT_RECENT_TURN_ID_LIMIT = 32;
3
- const PENDING_TURN_COMPLETION_FIELDS = [
4
- "schemaVersion",
5
- "taskId",
6
- "roleName",
7
- "agentId",
8
- "nativeSessionId",
9
- "turnId",
10
- "runId",
11
- "summary",
12
- "observedAt",
13
- "dueAt"
14
- ];
15
- export function createPendingTurnCompletion(input) {
16
- const observedAt = requireTimestamp(input.observedAt, "Turn observedAt");
17
- const dueAt = requireTimestamp(input.dueAt, "Turn dueAt");
18
- requireOrderedTimestamps(observedAt, dueAt);
19
- return {
20
- schemaVersion: 1,
21
- taskId: requireSafeIdentity(input.taskId, "Task id"),
22
- roleName: requireSafeIdentity(input.roleName, "Role name"),
23
- agentId: requireSafeIdentity(input.agentId, "Agent id"),
24
- nativeSessionId: requireText(input.nativeSessionId, "Native session id"),
25
- turnId: requireText(input.turnId, "Turn id"),
26
- runId: requireSafeIdentity(input.runId, "Run id"),
27
- summary: requireText(input.summary, "Turn summary"),
28
- observedAt,
29
- dueAt
30
- };
31
- }
32
- export function validatePendingTurnCompletion(value) {
33
- const input = requireRecord(value, "PendingTurnCompletion");
34
- requireExactFields(input, PENDING_TURN_COMPLETION_FIELDS, "PendingTurnCompletion");
35
- if (input.schemaVersion !== 1) {
36
- throw new Error("PendingTurnCompletion must use schemaVersion 1.");
37
- }
38
- const observedAt = requirePersistedTimestamp(input.observedAt, "PendingTurnCompletion observedAt");
39
- const dueAt = requirePersistedTimestamp(input.dueAt, "PendingTurnCompletion dueAt");
40
- requireOrderedTimestamps(observedAt, dueAt);
41
- return {
42
- schemaVersion: 1,
43
- taskId: requireSafeIdentityValue(input.taskId, "Task id"),
44
- roleName: requireSafeIdentityValue(input.roleName, "Role name"),
45
- agentId: requireSafeIdentityValue(input.agentId, "Agent id"),
46
- nativeSessionId: requireTextValue(input.nativeSessionId, "Native session id"),
47
- turnId: requireTextValue(input.turnId, "Turn id"),
48
- runId: requireSafeIdentityValue(input.runId, "Run id"),
49
- summary: requireTextValue(input.summary, "Turn summary"),
50
- observedAt,
51
- dueAt
52
- };
53
- }
54
- export function validateRecentTurnIds(value, limit = DEFAULT_RECENT_TURN_ID_LIMIT) {
55
- const normalizedLimit = requireLimit(limit);
56
- if (!Array.isArray(value))
57
- throw new Error("Recent Turn ids must be an array.");
58
- if (value.length > normalizedLimit) {
59
- throw new Error(`Recent Turn ids must not contain more than ${normalizedLimit} entries.`);
60
- }
61
- const result = value.map((turnId) => requireTextValue(turnId, "Recent Turn id"));
62
- if (new Set(result).size !== result.length) {
63
- throw new Error("Recent Turn ids must not contain duplicates.");
64
- }
65
- return result;
66
- }
67
- export function rememberRecentTurnId(recentTurnIds, turnId, limit = DEFAULT_RECENT_TURN_ID_LIMIT) {
68
- const normalizedLimit = requireLimit(limit);
69
- const existing = validateRecentTurnIds(recentTurnIds, normalizedLimit);
70
- const normalizedTurnId = requireText(turnId, "Recent Turn id");
71
- return [
72
- ...existing.filter((candidate) => candidate !== normalizedTurnId),
73
- normalizedTurnId
74
- ].slice(-normalizedLimit);
75
- }
76
- export function hasRecentTurnId(recentTurnIds, turnId) {
77
- const existing = validateRecentTurnIds(recentTurnIds);
78
- return existing.includes(requireText(turnId, "Recent Turn id"));
79
- }
80
- function requireOrderedTimestamps(observedAt, dueAt) {
81
- if (Date.parse(dueAt) < Date.parse(observedAt)) {
82
- throw new Error("PendingTurnCompletion dueAt must not be earlier than observedAt.");
83
- }
84
- }
85
- function requirePersistedTimestamp(value, label) {
86
- if (typeof value !== "string")
87
- throw new Error(`${label} must be a valid timestamp.`);
88
- const timestamp = Date.parse(value);
89
- if (!Number.isFinite(timestamp))
90
- throw new Error(`${label} must be a valid timestamp.`);
91
- const canonical = new Date(timestamp).toISOString();
92
- if (value !== canonical)
93
- throw new Error(`${label} must be a canonical timestamp.`);
94
- return canonical;
95
- }
96
- function requireRecord(value, label) {
97
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
98
- throw new Error(`${label} must be an object.`);
99
- }
100
- return value;
101
- }
102
- function requireExactFields(value, fields, label) {
103
- const expected = new Set(fields);
104
- const unknown = Object.keys(value).find((field) => !expected.has(field));
105
- if (unknown !== undefined)
106
- throw new Error(`${label} has unknown field: ${unknown}.`);
107
- const missing = fields.find((field) => !Object.hasOwn(value, field));
108
- if (missing !== undefined)
109
- throw new Error(`${label} is missing field: ${missing}.`);
110
- }
111
- function requireSafeIdentityValue(value, label) {
112
- if (typeof value !== "string")
113
- throw new Error(`${label} is invalid.`);
114
- return requireSafeIdentity(value, label);
115
- }
116
- function requireTextValue(value, label) {
117
- if (typeof value !== "string")
118
- throw new Error(`${label} is invalid.`);
119
- return requireText(value, label);
120
- }
121
- function requireLimit(value) {
122
- if (!Number.isInteger(value) || value < 1) {
123
- throw new Error("Recent Turn id limit must be a positive integer.");
124
- }
125
- return value;
126
- }
@@ -1 +0,0 @@
1
- export const TASK_FINAL_REVIEW_CONTRACT_REBOUND_EVENT = "review.task-final-contract-rebound";