maka-agent 0.2.0-dev.76.20261009 → 0.2.0-dev.78.20261010

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/README.md +1 -1
  2. package/README.zh-CN.md +3 -3
  3. package/dist/pi-tui-pickers.js +5 -2
  4. package/dist/pi-tui-runner.js +211 -33
  5. package/dist/runtime-host-session-driver.js +91 -13
  6. package/dist/session-catalog-limits.js +22 -0
  7. package/dist/session-driver.js +10 -0
  8. package/dist/tui-copy-catalog.js +15 -0
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@maka/core/dist/bot-chat-settings.js +3 -0
  11. package/node_modules/@maka/core/dist/bot-events.js +1 -8
  12. package/node_modules/@maka/core/dist/local-memory.js +38 -1
  13. package/node_modules/@maka/core/dist/scheduled-task.js +14 -15
  14. package/node_modules/@maka/core/dist/session.js +3 -0
  15. package/node_modules/@maka/core/dist/text-sanitize.js +8 -3
  16. package/node_modules/@maka/runtime/dist/agent-graph-supervisor-wake.js +115 -17
  17. package/node_modules/@maka/runtime/dist/agent-run.js +11 -0
  18. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +11 -0
  19. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +13 -5
  20. package/node_modules/@maka/runtime/dist/bots/proxied-fetch.js +29 -1
  21. package/node_modules/@maka/runtime/dist/computer-use-observation-text.js +22 -0
  22. package/node_modules/@maka/runtime/dist/conversation-copy-agent-output.js +227 -0
  23. package/node_modules/@maka/runtime/dist/conversation-copy.js +176 -46
  24. package/node_modules/@maka/runtime/dist/file-stable-write.js +15 -3
  25. package/node_modules/@maka/runtime/dist/filesystem-worker/resource-resolver.js +3 -1
  26. package/node_modules/@maka/runtime/dist/model-adapter.js +20 -1
  27. package/node_modules/@maka/runtime/dist/network/proxy-test.js +28 -1
  28. package/node_modules/@maka/runtime/dist/network/scoped-fetch-transport.js +13 -2
  29. package/node_modules/@maka/runtime/dist/owned-child-process.js +209 -0
  30. package/node_modules/@maka/runtime/dist/owned-process-main.js +183 -0
  31. package/node_modules/@maka/runtime/dist/pipe-process-driver.js +19 -25
  32. package/node_modules/@maka/runtime/dist/runtime-kernel.js +216 -8
  33. package/node_modules/@maka/runtime/dist/sandbox-boundary-tool.js +12 -0
  34. package/node_modules/@maka/runtime/dist/session-manager.js +156 -17
  35. package/node_modules/@maka/runtime/dist/shell-exec.js +18 -20
  36. package/node_modules/@maka/runtime/dist/shell-run-manager.js +2 -1
  37. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +279 -8
  38. package/node_modules/@maka/runtime/dist/stream-graph-schedule-reconcile.js +209 -37
  39. package/node_modules/@maka/runtime/dist/tool-availability.js +55 -18
  40. package/node_modules/@maka/runtime/dist/tool-call-snapshot.js +142 -0
  41. package/node_modules/@maka/runtime/dist/tool-runtime.js +27 -84
  42. package/node_modules/@maka/runtime/dist/workers/{filesystem-worker.js → filesystem-worker.mjs} +12 -1
  43. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +30 -6
  44. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  45. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +44 -13
  46. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +6 -0
  47. package/node_modules/@maka/runtime-host/dist/client/wsl-environment.js +4 -0
  48. package/node_modules/@maka/runtime-host/dist/protocol/index.js +5 -1
  49. package/node_modules/@maka/runtime-host/dist/protocol/message.js +1 -13
  50. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +46 -9
  51. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +1 -13
  52. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +1 -13
  53. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +4 -7
  54. package/node_modules/@maka/runtime-host/dist/server/archive-retention-coordinator.js +81 -105
  55. package/node_modules/@maka/runtime-host/dist/server/candidate.js +47 -40
  56. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +87 -67
  57. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +5 -1
  58. package/node_modules/@maka/runtime-host/dist/server/host-maintenance-guards.js +95 -0
  59. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +18 -8
  60. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +32 -3
  61. package/node_modules/@maka/runtime-host/dist/server/project-catalog-coordinator.js +2 -0
  62. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +109 -8
  63. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +20 -3
  64. package/node_modules/@maka/runtime-host/dist/server/session-background-activity.js +71 -0
  65. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +8 -4
  66. package/node_modules/@maka/runtime-host/dist/server/session-interaction-activity.js +78 -0
  67. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +56 -0
  68. package/node_modules/@maka/runtime-host/dist/server/session-revision-graph-references.js +16 -2
  69. package/node_modules/@maka/runtime-host/dist/server/skill-catalog-coordinator.js +2 -0
  70. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +19 -24
  71. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +74 -19
  72. package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +1 -1
  73. package/node_modules/@maka/runtime-host/dist/server/workhub-result-runtime.js +6 -99
  74. package/node_modules/@maka/runtime-host/dist/server/workhub-target-execution-authority.js +14 -126
  75. package/node_modules/@maka/storage/dist/context-offload-store.js +8 -3
  76. package/node_modules/@maka/storage/dist/git-entry.js +142 -5
  77. package/node_modules/@maka/storage/dist/session-bundle-policy.js +54 -19
  78. package/package.json +2 -2
@@ -777,6 +777,37 @@ export class RootTurnCoordinator {
777
777
  await disposition.active.done;
778
778
  });
779
779
  }
780
+ /**
781
+ * Activation-scoped graph stop: the same durable Host fence as `stopRoot`,
782
+ * but the Runtime stop reaches only this exact Run's owner, is redelivered
783
+ * after a failed attempt, and retries retained cleanup of a completed Run.
784
+ */
785
+ stopRootRun(identity, input = {}) {
786
+ normalizeStopSessionSource(input.source, input.workHubActionId);
787
+ return this.runCommand(async () => {
788
+ const declared = await this.sessionAdmission.run(identity.sessionId, (lease) => this.declareStopFence(identity, () => this.messages.commitStopFence(identity), lease, input, true));
789
+ await declared?.deliverStop();
790
+ await declared?.active.startSettled.promise;
791
+ const disposition = await this.sessionAdmission.run(identity.sessionId, (lease) => this.prepareStopDisposition(identity, () => this.messages.commitStopFence(identity), lease));
792
+ if (disposition.kind === 'complete') {
793
+ if (!disposition.outcome.ok)
794
+ throwHostedStopError(identity.sessionId, disposition.outcome);
795
+ const logical = await readLogicalRuntimeExecutionForRun(this.stores.runtimeEventStore, identity);
796
+ await this.deliverRuntimeStopIntent(identity.sessionId, input, {
797
+ ...identity,
798
+ runId: logical?.tip.runId ?? identity.runId,
799
+ });
800
+ return;
801
+ }
802
+ if (disposition.kind === 'request_stop') {
803
+ await this.deliverRuntimeStopIntent(identity.sessionId, input, {
804
+ ...identity,
805
+ runId: disposition.active.continuation?.runId ?? identity.runId,
806
+ });
807
+ }
808
+ await disposition.active.done;
809
+ });
810
+ }
780
811
  stopSession(sessionId, input = {}) {
781
812
  normalizeStopSessionSource(input.source, input.workHubActionId);
782
813
  return this.runCommand(async () => {
@@ -1828,7 +1859,7 @@ export class RootTurnCoordinator {
1828
1859
  },
1829
1860
  };
1830
1861
  }
1831
- async declareStopFence(input, commitQueueFence, admission, stopInput = {}) {
1862
+ async declareStopFence(input, commitQueueFence, admission, stopInput = {}, scoped = false) {
1832
1863
  const active = this.#executions.get(input.sessionId);
1833
1864
  if (!active || active.turnId !== input.turnId || active.runId !== input.runId) {
1834
1865
  return undefined;
@@ -1839,12 +1870,17 @@ export class RootTurnCoordinator {
1839
1870
  const fence = commitQueueFence();
1840
1871
  await this.messages.cancelMessages(input.sessionId, fence.retracted.map((message) => message.messageId));
1841
1872
  await this.interactions.claimRunClosure({ ...input, runId: active.continuation?.runId ?? active.runId }, 'turn_stopped', admission);
1842
- const shouldDeliverStop = !active.stopRequested;
1873
+ const shouldDeliverStop = scoped || !active.stopRequested;
1843
1874
  active.stopRequested = stopInput;
1844
1875
  return {
1845
1876
  active,
1846
1877
  deliverStop: () => shouldDeliverStop
1847
- ? this.deliverRuntimeStopIntent(input.sessionId, stopInput)
1878
+ ? this.deliverRuntimeStopIntent(input.sessionId, stopInput, scoped
1879
+ ? {
1880
+ ...input,
1881
+ runId: active.continuation?.runId ?? active.runId,
1882
+ }
1883
+ : undefined)
1848
1884
  : Promise.resolve(),
1849
1885
  };
1850
1886
  }
@@ -2039,13 +2075,65 @@ export class RootTurnCoordinator {
2039
2075
  result,
2040
2076
  };
2041
2077
  }
2078
+ async readExecutionPolicyForRun(sessionId, runId, visited = new Set()) {
2079
+ const identity = `${sessionId}:${runId}`;
2080
+ if (visited.has(identity))
2081
+ throw new Error('Cyclic execution policy lineage');
2082
+ visited.add(identity);
2083
+ const run = (await this.stores.runtimeEventStore.listSessionInvocations(sessionId)).find((candidate) => candidate.runId === runId);
2084
+ if (!run)
2085
+ return undefined;
2086
+ const policy = await this.readWorkHubExecutionPolicy(sessionId, run.turnId);
2087
+ if (policy)
2088
+ return policy;
2089
+ if (run.opening.source.kind === 'continuation')
2090
+ return this.readExecutionPolicyForRun(sessionId, run.opening.source.sourceRunId, visited);
2091
+ const [header, admission] = await Promise.all([
2092
+ this.stores.sessionStore.readHeaderSnapshot(sessionId),
2093
+ this.stores.agentRunStore.readRootTurnAdmission(sessionId, run.turnId),
2094
+ ]);
2095
+ const linkedExecution = header.subagentSpawn?.initialTurnId === run.turnId ||
2096
+ admission?.execution.kind === 'claimed_agent_graph_intent';
2097
+ return header.subagentParent && linkedExecution
2098
+ ? this.readExecutionPolicyForRun(header.subagentParent.parentSessionId, header.subagentParent.spawnedBy.parentRunId, visited)
2099
+ : undefined;
2100
+ }
2101
+ async readWorkHubExecutionPolicy(sessionId, turnId) {
2102
+ let admission = await this.stores.agentRunStore.readRootTurnAdmission(sessionId, turnId);
2103
+ if (!admission?.sourceMessages.length) {
2104
+ // Only continuations need an invocation walk to their original Message owner.
2105
+ const runs = await this.stores.runtimeEventStore.listSessionInvocations(sessionId);
2106
+ const visited = new Set();
2107
+ while (!visited.has(turnId)) {
2108
+ visited.add(turnId);
2109
+ const run = runs.find((candidate) => candidate.turnId === turnId);
2110
+ if (run?.opening.source.kind !== 'continuation')
2111
+ break;
2112
+ turnId = run.opening.source.sourceTurnId;
2113
+ }
2114
+ admission = await this.stores.agentRunStore.readRootTurnAdmission(sessionId, turnId);
2115
+ }
2116
+ const sources = new Set(admission?.sourceMessages.map((source) => source.messageId));
2117
+ // An ordinary external Turn has no sourceMessages. WorkHub steering is
2118
+ // still durable and belongs to that Turn through targetTurnId.
2119
+ const assignments = await this.stores.sessionStore.readActiveWorkHubAssignmentsByTarget([sessionId], undefined, true);
2120
+ const delegated = assignments.filter((assignment) => (sources.has(assignment.targetMessageId) ||
2121
+ (assignment.steered && assignment.targetTurnId === turnId)) &&
2122
+ assignment.executionPermissionMode !== undefined);
2123
+ const modes = new Set(delegated.map((assignment) => assignment.executionPermissionMode));
2124
+ if (modes.size > 1)
2125
+ throw new Error('Queued WorkHub messages have conflicting execution permissions');
2126
+ return delegated.length > 0
2127
+ ? { permissionMode: delegated[0].executionPermissionMode, questions: 'return' }
2128
+ : undefined;
2129
+ }
2042
2130
  /**
2043
2131
  * The one root path that carries a user Message. Session naming hangs here
2044
2132
  * rather than on the shared run-started hook: a compaction or a continuation
2045
2133
  * opens a Run without new words, and neither should name a Session.
2046
2134
  */
2047
- startRootMessageTurn(input, active, content, messageOrigin, onRunStarted) {
2048
- return this.manager.sendMessage(input.sessionId, {
2135
+ async *startRootMessageTurn(input, active, content, messageOrigin, onRunStarted, executionPolicy) {
2136
+ yield* this.manager.sendMessage(input.sessionId, {
2049
2137
  turnId: input.turnId,
2050
2138
  ...content,
2051
2139
  ...(active.descriptor.kind === 'regenerate'
@@ -2061,6 +2149,7 @@ export class RootTurnCoordinator {
2061
2149
  : {}),
2062
2150
  ...(messageOrigin ? { origin: messageOrigin } : {}),
2063
2151
  }, {
2152
+ ...(executionPolicy ? { executionPolicy } : {}),
2064
2153
  runId: active.runId,
2065
2154
  userMessageId: active.userMessageId,
2066
2155
  durability: 'required',
@@ -2077,6 +2166,13 @@ export class RootTurnCoordinator {
2077
2166
  let terminalTransitionStarted = false;
2078
2167
  let detached = false;
2079
2168
  try {
2169
+ const policyTurnId = active.continuation?.sourceTurnId ?? input.turnId;
2170
+ const executionPolicy = (await this.readWorkHubExecutionPolicy(input.sessionId, policyTurnId)) ??
2171
+ (active.descriptor.kind === 'linked_child_initial' ||
2172
+ active.descriptor.kind === 'claimed_agent_graph_intent' ||
2173
+ active.continuation
2174
+ ? await this.readExecutionPolicyForRun(input.sessionId, active.continuation?.sourceRunId ?? active.runId)
2175
+ : undefined);
2080
2176
  const messageOrigin = hostedExecutionMessageOrigin(active.descriptor);
2081
2177
  const onRunStarted = async () => {
2082
2178
  await this.manager.commitRevisionVersion(input.sessionId);
@@ -2085,6 +2181,7 @@ export class RootTurnCoordinator {
2085
2181
  };
2086
2182
  let stream = active.continuation
2087
2183
  ? this.manager.resumeSafeBoundaryContinuation(active.continuation, {
2184
+ executionPolicy,
2088
2185
  onRunStarted,
2089
2186
  stopBeforeDispatch: () => active.stopRequested,
2090
2187
  })
@@ -2107,9 +2204,10 @@ export class RootTurnCoordinator {
2107
2204
  })
2108
2205
  : active.continuation
2109
2206
  ? this.manager.resumeSafeBoundaryContinuation(active.continuation, {
2207
+ executionPolicy,
2110
2208
  onRunStarted,
2111
2209
  })
2112
- : this.startRootMessageTurn(input, active, normalizeMessageContent(requireRootMessageContent(input)), messageOrigin, onRunStarted);
2210
+ : this.startRootMessageTurn(input, active, normalizeMessageContent(requireRootMessageContent(input)), messageOrigin, onRunStarted, executionPolicy);
2113
2211
  for (;;) {
2114
2212
  for await (const event of stream) {
2115
2213
  if (active.execution?.onEvent) {
@@ -2154,6 +2252,9 @@ export class RootTurnCoordinator {
2154
2252
  active.continuation = plan.continuation;
2155
2253
  });
2156
2254
  stream = this.manager.resumeSafeBoundaryContinuation(active.continuation, {
2255
+ // WorkHub can steer an ordinary Turn after its initial policy was
2256
+ // captured. A physical successor stays in that execution lineage.
2257
+ executionPolicy: await this.readExecutionPolicyForRun(input.sessionId, active.continuation.sourceRunId),
2157
2258
  onRunStarted,
2158
2259
  stopBeforeDispatch: () => active.stopRequested,
2159
2260
  });
@@ -2358,8 +2459,8 @@ export class RootTurnCoordinator {
2358
2459
  throw new RuntimeMessageAuthorityInvariantError('Fresh follow-up root Turn did not reserve execution');
2359
2460
  }
2360
2461
  }
2361
- async deliverRuntimeStopIntent(sessionId, input = { source: 'stop_button' }) {
2362
- await this.manager.deliverHostedRootStop(sessionId, input);
2462
+ async deliverRuntimeStopIntent(sessionId, input = { source: 'stop_button' }, identity) {
2463
+ await this.manager.deliverHostedRootStop(sessionId, input, identity);
2363
2464
  }
2364
2465
  async stopActiveTurn(sessionId, active) {
2365
2466
  await this.stopRoot({
@@ -344,8 +344,13 @@ export class HostScheduledTaskCoordinator {
344
344
  const claim = await this.#store.claimNow(input.taskId, this.#now());
345
345
  await this.#refreshResidency();
346
346
  const task = await this.#fulfill(claim, false);
347
- if (!task)
347
+ if (!task) {
348
+ // The waiting claim is already durable. A Store failure here
349
+ // drains the Host and recovery retries the claim, so the caller
350
+ // still gets the provider outcome rather than a generic failure.
351
+ await this.#refreshSchedule().catch((error) => this.#fatal(error));
348
352
  throw new ScheduledTaskNativeUnavailableError();
353
+ }
349
354
  return task;
350
355
  }));
351
356
  }
@@ -464,6 +469,11 @@ export class HostScheduledTaskCoordinator {
464
469
  if (recovering && claim.nativeState !== 'waiting_for_provider') {
465
470
  return this.#settleFailure(claim, 'The previous native notification stopped before delivery was confirmed.');
466
471
  }
472
+ // Expiry closes delivery just as it closes due and Trigger Now admission.
473
+ // A fire still waiting for a provider is settled rather than sent late.
474
+ if (task.expiresAt !== null && this.#now() >= task.expiresAt) {
475
+ return this.#settle(claim, 'blocked', '定时任务已过期,通知没有送达。', 'blocked');
476
+ }
467
477
  if (task.effect.channel === 'bot' && !isBotDeliveryProvider(task.effect.platform)) {
468
478
  return this.#settle(claim, 'blocked', `${botDisplayLabel(task.effect.platform)} 当前不是可投递目标。`, 'blocked');
469
479
  }
@@ -666,10 +676,17 @@ export class HostScheduledTaskCoordinator {
666
676
  if (!this.#started || this.#draining || this.#handoffHeld)
667
677
  return;
668
678
  const [tasks, claims] = await Promise.all([this.#store.list(), this.#store.listPendingFires()]);
679
+ const claimedTaskIds = new Set(claims.map((claim) => claim.task.id));
669
680
  const next = tasks
670
- .filter((task) => task.status === 'active' && task.nextFireAt !== null)
681
+ .filter((task) => task.status === 'active')
671
682
  .reduce((earliest, task) => {
672
- const deadline = Math.min(task.nextFireAt, task.expiresAt ?? task.nextFireAt);
683
+ // A claimed fire waits on delivery, not on its original due time. Its
684
+ // expiry still wakes the scheduler, which settles a fire that is still
685
+ // waiting for a provider as blocked.
686
+ const nextFireAt = claimedTaskIds.has(task.id) ? null : task.nextFireAt;
687
+ const deadline = nextFireAt === null ? task.expiresAt : Math.min(nextFireAt, task.expiresAt ?? nextFireAt);
688
+ if (deadline === null)
689
+ return earliest;
673
690
  return earliest === null || deadline < earliest ? deadline : earliest;
674
691
  }, null);
675
692
  const waitingForProvider = claims.some((claim) => claim.nativeState === 'waiting_for_provider');
@@ -0,0 +1,71 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ /**
20
+ * One read projection for initial catalog queries and subsequent invalidations.
21
+ * The execution coordinators own the facts; this only remembers the last
22
+ * published value so handoffs between Graph and supervisor do not churn lists.
23
+ * Its lifetime is one Host epoch and it never persists a running flag.
24
+ */
25
+ export class SessionBackgroundActivityProjection {
26
+ sources;
27
+ #published = new Map();
28
+ // Keep idle tombstones for this Host generation: forgetting a Session's
29
+ // clock would let an older running response outrank its newer idle state.
30
+ // Only Sessions with an activity transition allocate an entry, and the
31
+ // Host-scoped projection releases these clocks when its generation ends.
32
+ #revisions = new Map();
33
+ constructor(sources) {
34
+ this.sources = sources;
35
+ }
36
+ read(sessionId) {
37
+ const graph = this.sources.graph(sessionId);
38
+ const supervisor = this.sources.supervisor(sessionId);
39
+ if (graph === 'waiting_for_user' || supervisor === 'waiting_for_user')
40
+ return 'waiting_for_user';
41
+ // A supervisor may be handling a failed child without needing the user.
42
+ if (graph === 'running' || supervisor === 'running')
43
+ return 'running';
44
+ if (graph === 'blocked' || supervisor === 'blocked')
45
+ return 'blocked';
46
+ return 'idle';
47
+ }
48
+ snapshot(sessionId) {
49
+ return {
50
+ backgroundActivity: this.read(sessionId),
51
+ backgroundActivityVersion: {
52
+ hostGeneration: this.sources.hostGeneration,
53
+ revision: this.#revisions.get(sessionId) ?? 0,
54
+ },
55
+ };
56
+ }
57
+ changed(sessionId) {
58
+ const next = this.read(sessionId);
59
+ const previous = this.#published.get(sessionId) ?? 'idle';
60
+ if (previous === next)
61
+ return;
62
+ // Guests can read their shared Session's version, so its clock must not
63
+ // expose transitions in other Sessions on the same Host.
64
+ this.#revisions.set(sessionId, (this.#revisions.get(sessionId) ?? 0) + 1);
65
+ if (next === 'idle')
66
+ this.#published.delete(sessionId);
67
+ else
68
+ this.#published.set(sessionId, next);
69
+ this.sources.publish(sessionId);
70
+ }
71
+ }
@@ -148,6 +148,7 @@ export class HostSessionCatalogCoordinator {
148
148
  #runtimePolicy;
149
149
  #manager;
150
150
  #isTurnBusy;
151
+ #readBackgroundActivity;
151
152
  #admission;
152
153
  #continuity;
153
154
  #workspaceResolver;
@@ -162,6 +163,7 @@ export class HostSessionCatalogCoordinator {
162
163
  this.#runtimePolicy = options.runtimePolicy;
163
164
  this.#manager = options.manager;
164
165
  this.#isTurnBusy = options.isTurnBusy;
166
+ this.#readBackgroundActivity = options.readBackgroundActivity;
165
167
  this.#admission = options.admission;
166
168
  this.#continuity = options.continuity;
167
169
  this.#workspaceResolver = options.workspaceResolver;
@@ -305,7 +307,7 @@ export class HostSessionCatalogCoordinator {
305
307
  ok: true,
306
308
  result: {
307
309
  session: record
308
- ? projectSharedSessionCatalogRecord(record, projectCatalogLiveRunState(this.#manager.runningTurnIds(record.header.id), this.#manager.sessionRunEpoch(record.header.id), this.#manager.sessionHostGeneration()))
310
+ ? projectSharedSessionCatalogRecord(record, projectCatalogLiveRunState(this.#manager.runningTurnIds(record.header.id), this.#manager.sessionRunEpoch(record.header.id), this.#manager.sessionHostGeneration()), this.#readBackgroundActivity?.(record.header.id))
309
311
  : null,
310
312
  },
311
313
  };
@@ -318,7 +320,7 @@ export class HostSessionCatalogCoordinator {
318
320
  }
319
321
  }
320
322
  #projectCatalogQueryRecord(record) {
321
- return projectSessionCatalogRecord(record, projectCatalogLiveRunState(this.#manager.runningTurnIds(record.header.id), this.#manager.sessionRunEpoch(record.header.id), this.#manager.sessionHostGeneration()));
323
+ return projectSessionCatalogRecord(record, projectCatalogLiveRunState(this.#manager.runningTurnIds(record.header.id), this.#manager.sessionRunEpoch(record.header.id), this.#manager.sessionHostGeneration()), this.#readBackgroundActivity?.(record.header.id));
322
324
  }
323
325
  async #queryExecutionBoundary(input) {
324
326
  try {
@@ -1121,7 +1123,7 @@ function createRequestFingerprint(input, prepared) {
1121
1123
  ];
1122
1124
  return `sha256:${createHash('sha256').update(JSON.stringify(identity)).digest('hex')}`;
1123
1125
  }
1124
- export function projectSessionCatalogRecord(record, liveRunState) {
1126
+ export function projectSessionCatalogRecord(record, liveRunState, backgroundActivity) {
1125
1127
  const { header, summary } = record;
1126
1128
  const projectedLabels = projectCatalogLabels(header.labels);
1127
1129
  const projection = {
@@ -1156,6 +1158,7 @@ export function projectSessionCatalogRecord(record, liveRunState) {
1156
1158
  : { lastMessagePreview: summary.lastMessagePreview }),
1157
1159
  status: header.status,
1158
1160
  ...(liveRunState === undefined ? {} : { liveRunState }),
1161
+ ...(backgroundActivity === undefined ? {} : backgroundActivity),
1159
1162
  ...(header.blockedReason === undefined ? {} : { blockedReason: header.blockedReason }),
1160
1163
  ...(header.statusUpdatedAt === undefined ? {} : { statusUpdatedAt: header.statusUpdatedAt }),
1161
1164
  ...(header.parentSessionId === undefined ? {} : { parentSessionId: header.parentSessionId }),
@@ -1215,7 +1218,7 @@ export function projectSessionCatalogRecord(record, liveRunState) {
1215
1218
  };
1216
1219
  }
1217
1220
  }
1218
- function projectSharedSessionCatalogRecord(record, liveRunState) {
1221
+ function projectSharedSessionCatalogRecord(record, liveRunState, backgroundActivity) {
1219
1222
  const { header, summary } = record;
1220
1223
  const shared = {
1221
1224
  kind: 'shared_session',
@@ -1230,6 +1233,7 @@ function projectSharedSessionCatalogRecord(record, liveRunState) {
1230
1233
  : { lastMessagePreview: summary.lastMessagePreview }),
1231
1234
  status: header.status,
1232
1235
  ...(liveRunState === undefined ? {} : { liveRunState }),
1236
+ ...(backgroundActivity === undefined ? {} : backgroundActivity),
1233
1237
  ...(header.blockedReason === undefined ? {} : { blockedReason: header.blockedReason }),
1234
1238
  ...(header.statusUpdatedAt === undefined ? {} : { statusUpdatedAt: header.statusUpdatedAt }),
1235
1239
  };
@@ -0,0 +1,78 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ /**
20
+ * Process-local read projection of the canonical pending requests. Refreshes run
21
+ * under the Interaction coordinator's Session admission, including withdrawals
22
+ * that have no Runtime answer event. Catalog reads never query these stores.
23
+ */
24
+ export class SessionInteractionActivityProjection {
25
+ sources;
26
+ #counts = new Map();
27
+ constructor(sources) {
28
+ this.sources = sources;
29
+ }
30
+ readTurnPendingInteractionCount(sessionId, turnId) {
31
+ const counts = this.#counts.get(sessionId);
32
+ return counts ? (counts.get(turnId) ?? 0) : undefined;
33
+ }
34
+ async refresh(sessionId) {
35
+ try {
36
+ await this.#refresh(sessionId);
37
+ }
38
+ catch (error) {
39
+ // This is presentation state, not canonical authority. Failed reads must
40
+ // neither retain authoritative counts nor prevent an answer from applying.
41
+ const invalidated = this.#counts.delete(sessionId);
42
+ try {
43
+ if (invalidated)
44
+ this.sources.onChanged(sessionId);
45
+ }
46
+ catch {
47
+ // A catalog observer cannot gate canonical continuity either.
48
+ }
49
+ try {
50
+ this.sources.onError(sessionId, error);
51
+ }
52
+ catch {
53
+ // Diagnostics must not turn a presentation failure into an authority failure.
54
+ }
55
+ }
56
+ }
57
+ async #refresh(sessionId) {
58
+ const [interactions, boundaries] = await Promise.all([
59
+ this.sources.interactions.listSessionPending(sessionId),
60
+ this.sources.sandboxBoundaries.listPendingSandboxBoundaryRequests(sessionId),
61
+ ]);
62
+ const counts = new Map();
63
+ for (const request of [...interactions, ...boundaries]) {
64
+ // Handoffs replace the physical run id while retaining this logical Turn.
65
+ // A new graph activation has a different Turn and cannot inherit its wait.
66
+ if (request.turnId === undefined)
67
+ continue;
68
+ counts.set(request.turnId, (counts.get(request.turnId) ?? 0) + 1);
69
+ }
70
+ const previous = this.#counts.get(sessionId);
71
+ if (previous?.size === counts.size &&
72
+ [...counts].every(([turnId, count]) => previous.get(turnId) === count)) {
73
+ return;
74
+ }
75
+ this.#counts.set(sessionId, counts);
76
+ this.sources.onChanged(sessionId);
77
+ }
78
+ }
@@ -23,6 +23,8 @@ import { HostScheduledTaskSessionBusyError, } from './scheduled-task-coordinator
23
23
  import { projectSessionCatalogRecord } from './session-catalog-coordinator.js';
24
24
  import { purgeSessionSidecars } from './session-sidecar-purge.js';
25
25
  const FAMILY_STABILIZATION_ATTEMPTS = 4;
26
+ /** The store rejects a WorkHub target batch above its own bound; page below it. */
27
+ const WORKHUB_ASSIGNMENT_TARGET_PAGE = 256;
26
28
  class RetryFamilyResolution extends Error {
27
29
  sessionIds;
28
30
  name = 'RetryFamilyResolution';
@@ -66,6 +68,7 @@ export class HostSessionRetirementCoordinator {
66
68
  #root;
67
69
  #messages;
68
70
  #interactions;
71
+ #workHub;
69
72
  #goals;
70
73
  #scheduledTasks;
71
74
  #resources;
@@ -95,6 +98,7 @@ export class HostSessionRetirementCoordinator {
95
98
  this.#root = options.root;
96
99
  this.#messages = options.messages;
97
100
  this.#interactions = options.interactions;
101
+ this.#workHub = options.workHub;
98
102
  this.#goals = options.goals;
99
103
  this.#scheduledTasks = options.scheduledTasks;
100
104
  this.#resources = options.resources;
@@ -150,6 +154,7 @@ export class HostSessionRetirementCoordinator {
150
154
  let handles;
151
155
  let committed = false;
152
156
  try {
157
+ await this.#assertNoLiveRelationships(family);
153
158
  handles = await this.#prepareRetirement(family, 'archive');
154
159
  await this.#finalizeWorkspacePatches(family.sessionIds);
155
160
  await this.#disposeBackends(family.sessionIds);
@@ -563,6 +568,57 @@ export class HostSessionRetirementCoordinator {
563
568
  expectedVersion: record.revision,
564
569
  })), true);
565
570
  }
571
+ /**
572
+ * A manual archive must not hide a Session that a WorkHub delegation or a
573
+ * linked child still points at: WorkHub candidate and result views exclude
574
+ * archived Sessions, so either relationship would lose its visible target.
575
+ * "Live" means the relationship is still in flight — the delegation's
576
+ * execution has not retired (or its result has not been delivered), or the
577
+ * child still carries active work. A finished delegation and a finished
578
+ * subtask hold nothing visible hostage, so they no longer block the archive.
579
+ * This guards the manual archive path only — a removal retires or archives
580
+ * the whole relationship set under its own confirm.
581
+ */
582
+ async #assertNoLiveRelationships(family) {
583
+ const familyIds = new Set(family.sessionIds);
584
+ for (let offset = 0; offset < family.sessionIds.length; offset += WORKHUB_ASSIGNMENT_TARGET_PAGE) {
585
+ const page = family.sessionIds.slice(offset, offset + WORKHUB_ASSIGNMENT_TARGET_PAGE);
586
+ // The ledger keeps every live delegation of a target, newest first, so a
587
+ // finished newest delegation must not hide an older one that is still in
588
+ // flight or still owes WorkHub its result.
589
+ const assignments = await this.#stores.readActiveWorkHubAssignmentsByTarget(page);
590
+ for (const assignment of assignments) {
591
+ // The Coordination ledger keeps a delegation row until it is superseded
592
+ // or stopped, so the row alone says nothing about the work: read the
593
+ // delegation's execution state the same way WorkHub actions do.
594
+ const retirement = await this.#workHub.readDelegationRetirement(assignment, family.admission);
595
+ if (retirement !== 'retired') {
596
+ throw new SessionRetirementBusyError(`Session ${assignment.targetSessionId} has an active WorkHub delegation`);
597
+ }
598
+ if (await this.#workHub.hasUndeliveredResult(assignment, family.admission)) {
599
+ throw new SessionRetirementBusyError(`Session ${assignment.targetSessionId} has an undelivered WorkHub result`);
600
+ }
601
+ }
602
+ }
603
+ for (const header of await this.#stores.listHeaders()) {
604
+ const parent = header.subagentParent;
605
+ if (parent === undefined || parent.graph !== undefined)
606
+ continue;
607
+ if (!familyIds.has(parent.parentSessionId))
608
+ continue;
609
+ if (header.conversationCopy?.state === 'preparing' || header.isArchived)
610
+ continue;
611
+ if (await this.#hasLiveChildWork(header.id)) {
612
+ throw new SessionRetirementBusyError(`Session ${parent.parentSessionId} has a live linked child Session`);
613
+ }
614
+ }
615
+ }
616
+ /** The in-flight signals that make a linked child worth keeping visible. */
617
+ async #hasLiveChildWork(sessionId) {
618
+ return (this.#root.readRootState(sessionId).kind !== 'idle' ||
619
+ this.#messages.hasLiveSessionState(sessionId) ||
620
+ (await this.#interactions.hasPendingSession(sessionId)));
621
+ }
566
622
  async #prepareRetirement(family, kind) {
567
623
  for (const sessionId of family.sessionIds) {
568
624
  if (this.#root.readRootState(sessionId).kind !== 'idle') {
@@ -88,6 +88,7 @@ export async function prepareLinkedChildCopyReferences(input, dependencies) {
88
88
  const shared = new Map();
89
89
  const snapshots = new Map();
90
90
  const runsByChildSession = new Map();
91
+ const terminalResults = new Set(requests.filter((request) => isTerminalRunStatus(request.status)).map(linkedRunKey));
91
92
  for (const request of requests) {
92
93
  const childSessionId = request.childSessionId;
93
94
  const child = headersById.get(childSessionId);
@@ -95,13 +96,21 @@ export async function prepareLinkedChildCopyReferences(input, dependencies) {
95
96
  if (!child ||
96
97
  !parent ||
97
98
  !familySessionIds.has(parent.parentSessionId) ||
99
+ (request.graph !== undefined &&
100
+ (request.graph.graphId !== parent.graph?.graphId ||
101
+ request.graph.workId !== parent.graph?.workId ||
102
+ request.graph.operatorId !== parent.graph?.operatorId)) ||
98
103
  !retainedTurnIds.has(parent.spawnedBy.parentTurnId)) {
99
104
  return failure('operation_unavailable', 'Linked child reference does not belong to the source revision family');
100
105
  }
101
106
  if (dependencies.isSessionActive(childSessionId)) {
102
107
  return failure('session_busy', 'A retained linked child is still active');
103
108
  }
104
- if (!isTerminalRunStatus(request.status)) {
109
+ // A poll describes the run at read time. It may precede a retained terminal
110
+ // result for that exact run, but cannot borrow one from another execution.
111
+ // Keep validating every observation, including its Artifact references.
112
+ const terminalResult = isTerminalRunStatus(request.status);
113
+ if (!terminalResult && !terminalResults.has(linkedRunKey(request))) {
105
114
  return failure('session_busy', 'A retained linked child result is not terminal');
106
115
  }
107
116
  let runsById = runsByChildSession.get(childSessionId);
@@ -126,7 +135,9 @@ export async function prepareLinkedChildCopyReferences(input, dependencies) {
126
135
  if (!currentRun ||
127
136
  currentRun.sessionId !== childSessionId ||
128
137
  currentRun.turnId !== request.turnId ||
129
- !linkedResultStatusMatchesRun(request, currentRun)) {
138
+ (request.terminalEventId !== undefined &&
139
+ request.terminalEventId !== currentRun.terminalEvent?.id) ||
140
+ (terminalResult && !linkedResultStatusMatchesRun(request, currentRun))) {
130
141
  return failure('operation_unavailable', 'Retained linked child run reference is unavailable');
131
142
  }
132
143
  const lineage = traceChildRunLineage(currentRun, runsById, childSessionId);
@@ -166,6 +177,9 @@ export async function prepareLinkedChildCopyReferences(input, dependencies) {
166
177
  }
167
178
  return { ok: true, shared, snapshots };
168
179
  }
180
+ function linkedRunKey(reference) {
181
+ return JSON.stringify([reference.childSessionId, reference.runId, reference.turnId]);
182
+ }
169
183
  export function linkedChildCopyAdmissionSessionIds(input) {
170
184
  const retainedTurnIds = new Set(input.copyTurnIds);
171
185
  const sessionIds = new Set(input.requests.map((request) => request.childSessionId));
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { reportUnexpectedOperation } from '@maka/core/redaction';
19
20
  import { SkillCatalogRepositoryError, } from './skill-catalog-repository.js';
20
21
  import { WorkspaceResolutionError, } from './workspace-resolver.js';
21
22
  export class SkillCatalogInvocableContextError extends Error {
@@ -168,6 +169,7 @@ function repositoryFailure(operation, error) {
168
169
  error: { code: 'invalid_request', message: error.message },
169
170
  };
170
171
  }
172
+ reportUnexpectedOperation(`runtime-host:skill-catalog:${operation}`, error);
171
173
  return {
172
174
  ok: false,
173
175
  error: { code: 'internal_failure', message: 'Skill catalog operation failed' },