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

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 (40) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  4. package/node_modules/@maka/runtime/dist/agent-graph-supervisor-wake.js +115 -17
  5. package/node_modules/@maka/runtime/dist/agent-run.js +11 -0
  6. package/node_modules/@maka/runtime/dist/computer-use-observation-text.js +22 -0
  7. package/node_modules/@maka/runtime/dist/conversation-copy-agent-output.js +227 -0
  8. package/node_modules/@maka/runtime/dist/conversation-copy.js +176 -46
  9. package/node_modules/@maka/runtime/dist/filesystem-worker/resource-resolver.js +3 -1
  10. package/node_modules/@maka/runtime/dist/owned-child-process.js +209 -0
  11. package/node_modules/@maka/runtime/dist/owned-process-main.js +183 -0
  12. package/node_modules/@maka/runtime/dist/pipe-process-driver.js +19 -25
  13. package/node_modules/@maka/runtime/dist/runtime-kernel.js +124 -3
  14. package/node_modules/@maka/runtime/dist/session-manager.js +125 -12
  15. package/node_modules/@maka/runtime/dist/shell-exec.js +18 -20
  16. package/node_modules/@maka/runtime/dist/shell-run-manager.js +2 -1
  17. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +279 -8
  18. package/node_modules/@maka/runtime/dist/stream-graph-schedule-reconcile.js +209 -37
  19. package/node_modules/@maka/runtime/dist/tool-availability.js +37 -6
  20. package/node_modules/@maka/runtime/dist/tool-runtime.js +2 -1
  21. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +44 -13
  22. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +6 -0
  23. package/node_modules/@maka/runtime-host/dist/client/wsl-environment.js +4 -0
  24. package/node_modules/@maka/runtime-host/dist/protocol/index.js +4 -1
  25. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +46 -9
  26. package/node_modules/@maka/runtime-host/dist/server/candidate.js +47 -40
  27. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +70 -24
  28. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +5 -1
  29. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +41 -5
  30. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +20 -3
  31. package/node_modules/@maka/runtime-host/dist/server/session-background-activity.js +71 -0
  32. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +8 -4
  33. package/node_modules/@maka/runtime-host/dist/server/session-interaction-activity.js +78 -0
  34. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +56 -0
  35. package/node_modules/@maka/runtime-host/dist/server/session-revision-graph-references.js +16 -2
  36. package/node_modules/@maka/runtime-host/dist/server/workhub-result-runtime.js +3 -1
  37. package/node_modules/@maka/storage/dist/context-offload-store.js +8 -3
  38. package/node_modules/@maka/storage/dist/session-bundle-policy.js +54 -19
  39. package/package.json +2 -2
  40. /package/node_modules/@maka/runtime/dist/workers/{filesystem-worker.js → filesystem-worker.mjs} +0 -0
@@ -0,0 +1,183 @@
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
+ import { spawn } from 'node:child_process';
20
+ import { terminateProcessTree } from './process-tree-terminator.js';
21
+ let command;
22
+ let stopping = false;
23
+ let completed = false;
24
+ let ownerLost = false;
25
+ let finishing = false;
26
+ function loseOwner() {
27
+ if (completed || ownerLost)
28
+ return;
29
+ ownerLost = true;
30
+ stopping = true;
31
+ // This process is the POSIX group leader; the command joins its group. The
32
+ // Windows implementation uses taskkill /T. Discovery also includes descendants
33
+ // that have moved into another process group while still attached to this tree.
34
+ void terminateProcessTree({
35
+ pid: process.pid,
36
+ signal: 'SIGKILL',
37
+ fallback: () => process.exit(1),
38
+ }).then(() => process.exit(1), () => process.exit(1));
39
+ }
40
+ /** An unexpected supervisor error. Stopping the tree ends this process with
41
+ * its own group's SIGKILL, which the Host cannot tell from a forced stop, so
42
+ * report the fault first while the lease is still up. */
43
+ function fault(error) {
44
+ if (completed || ownerLost)
45
+ return;
46
+ // The command has exited and its result is already on the way; a fault
47
+ // now must not turn it into a failure. Only make sure this process ends.
48
+ if (finishing) {
49
+ setTimeout(() => process.exit(1), 1_000);
50
+ return;
51
+ }
52
+ if (!process.connected) {
53
+ loseOwner();
54
+ return;
55
+ }
56
+ // The tree stops whether or not the report goes through.
57
+ setTimeout(loseOwner, 1_000);
58
+ const message = error instanceof Error ? error.message : String(error);
59
+ try {
60
+ process.send({ kind: 'failed', message: `Command supervisor failed: ${message}` }, () => loseOwner());
61
+ }
62
+ catch {
63
+ loseOwner();
64
+ }
65
+ }
66
+ process.on('disconnect', loseOwner);
67
+ process.on('uncaughtException', fault);
68
+ process.on('unhandledRejection', fault);
69
+ // The command shares this process group, so a group-wide signal its own script
70
+ // sends (`kill -HUP 0`) reaches the supervisor too. Ignore the ones whose
71
+ // default action would end it, or for SIGUSR1 start the inspector, so the
72
+ // command alone decides how to handle them. Windows cannot listen for these.
73
+ if (process.platform !== 'win32') {
74
+ for (const signal of ['SIGHUP', 'SIGUSR1', 'SIGUSR2', 'SIGQUIT', 'SIGALRM']) {
75
+ process.on(signal, () => { });
76
+ }
77
+ }
78
+ for (const signal of ['SIGTERM', 'SIGINT']) {
79
+ process.on(signal, () => {
80
+ stopping = true;
81
+ // On POSIX the Host signals our entire group, including the command. Do not
82
+ // forward the signal a second time. Before admission, stop without spawning.
83
+ if (!command)
84
+ finish(null, signal);
85
+ });
86
+ }
87
+ function send(message, then) {
88
+ if (!process.connected) {
89
+ loseOwner();
90
+ return;
91
+ }
92
+ process.send(message, (error) => {
93
+ if (error)
94
+ loseOwner();
95
+ else
96
+ then?.();
97
+ });
98
+ }
99
+ function finish(code, signal) {
100
+ finishing = true;
101
+ send({ kind: 'completed' }, () => {
102
+ completed = true;
103
+ if (signal)
104
+ exitWithSignal(signal);
105
+ else
106
+ process.exit(code ?? 1);
107
+ });
108
+ }
109
+ /** Mirror the command's terminating signal. Node ignores SIGPIPE and reserves
110
+ * SIGUSR1 for its inspector even without listeners; removing a listener resets
111
+ * the handler to the default action, so the re-raised signal ends this process.
112
+ */
113
+ function exitWithSignal(signal) {
114
+ process.removeAllListeners(signal);
115
+ try {
116
+ process.on(signal, () => { });
117
+ process.removeAllListeners(signal);
118
+ }
119
+ catch {
120
+ // SIGKILL and SIGSTOP accept no listener; their default action already applies.
121
+ }
122
+ process.kill(process.pid, signal);
123
+ // Never outlive the command if the signal did not end this process.
124
+ setTimeout(() => process.exit(1), 1_000);
125
+ }
126
+ if (!process.connected)
127
+ process.exit(1);
128
+ process.once('message', (message) => {
129
+ if (!process.connected) {
130
+ loseOwner();
131
+ return;
132
+ }
133
+ // A stop that arrived before the launch is already finishing.
134
+ if (stopping)
135
+ return;
136
+ const input = message;
137
+ if (input.kind !== 'launch') {
138
+ loseOwner();
139
+ return;
140
+ }
141
+ // A group signal can be pending in this loop turn alongside the launch.
142
+ // Spawn in the check phase, after its handler has run, so a stop that
143
+ // arrived first ends the supervisor without starting the command.
144
+ setImmediate(() => {
145
+ if (stopping)
146
+ return;
147
+ if (!process.connected) {
148
+ loseOwner();
149
+ return;
150
+ }
151
+ launch(input);
152
+ });
153
+ });
154
+ function launch(input) {
155
+ const stdio = [0, 1, 2];
156
+ for (const fd of input.inheritedFds) {
157
+ while (stdio.length <= fd)
158
+ stdio.push('ignore');
159
+ stdio[fd] = fd;
160
+ }
161
+ try {
162
+ command = spawn(input.program, [...input.args], {
163
+ cwd: input.cwd,
164
+ env: input.env,
165
+ shell: input.shell,
166
+ stdio,
167
+ detached: false,
168
+ windowsHide: true,
169
+ });
170
+ command.once('spawn', () => send({ kind: 'started', pid: command?.pid }));
171
+ command.once('error', failed);
172
+ command.once('exit', finish);
173
+ }
174
+ catch (error) {
175
+ failed(error);
176
+ }
177
+ }
178
+ function failed(error) {
179
+ send({ kind: 'failed', message: error.message, code: error.code }, () => {
180
+ completed = true;
181
+ process.exit(1);
182
+ });
183
+ }
@@ -16,11 +16,12 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { spawn } from 'node:child_process';
20
- import { buildSpawnStdio, closeChildFdSources, writeChildFdInputs, } from './child-fd-input.js';
19
+ import { signalOwnedProcess, spawnOwnedProcess } from './owned-child-process.js';
20
+ import { closeChildFdSources, writeChildFdInputs } from './child-fd-input.js';
21
21
  import { trackCapturedOutputDrain, } from './child-process-lifecycle.js';
22
22
  export class PipeProcessDriver {
23
23
  options;
24
+ /** Supervisor PID; it leads the command's process group, so signals target it. */
24
25
  pid;
25
26
  ready;
26
27
  child;
@@ -34,16 +35,24 @@ export class PipeProcessDriver {
34
35
  rootExit;
35
36
  stdinSettled;
36
37
  stdinError;
38
+ admittedPid;
37
39
  constructor(options) {
38
40
  this.options = options;
39
41
  try {
40
- this.child = spawn(options.plan.file, options.plan.args, {
42
+ const spawned = spawnOwnedProcess({
43
+ program: options.plan.file,
44
+ args: options.plan.args,
41
45
  cwd: options.cwd,
42
46
  env: options.env,
43
47
  shell: options.plan.useShellOption,
44
- stdio: buildSpawnStdio(options.fdInputs, options.plan.stdin === undefined ? 'ignore' : 'pipe'),
45
- detached: process.platform !== 'win32',
48
+ stdin: options.plan.stdin === undefined ? 'ignore' : 'pipe',
49
+ fdInputs: options.fdInputs,
46
50
  });
51
+ this.child = spawned.child;
52
+ this.ready = spawned.ready.then((pid) => {
53
+ this.admittedPid = pid;
54
+ });
55
+ void this.ready.catch(() => { });
47
56
  }
48
57
  finally {
49
58
  closeChildFdSources(options.fdInputs);
@@ -78,7 +87,10 @@ export class PipeProcessDriver {
78
87
  this.child.on('exit', this.onRootExit);
79
88
  this.child.on('close', this.onCloseFallback);
80
89
  this.child.on('error', this.onError);
81
- this.ready = waitForSpawn(this.child);
90
+ }
91
+ /** The command's own PID, known once `ready` resolves; this is what users see. */
92
+ get commandPid() {
93
+ return this.admittedPid;
82
94
  }
83
95
  writeInputs() {
84
96
  writeChildFdInputs(this.child, this.options.fdInputs);
@@ -88,7 +100,7 @@ export class PipeProcessDriver {
88
100
  this.stdin.end(this.options.plan.stdin, this.onStdinEnd);
89
101
  }
90
102
  kill(signal) {
91
- return this.child.kill(signal);
103
+ return signalOwnedProcess(this.child, signal);
92
104
  }
93
105
  dispose() {
94
106
  if (this.disposed)
@@ -157,21 +169,3 @@ export class PipeProcessDriver {
157
169
  this.settleAfterDrain();
158
170
  };
159
171
  }
160
- function waitForSpawn(child) {
161
- return new Promise((resolve, reject) => {
162
- const onSpawn = () => {
163
- cleanup();
164
- resolve();
165
- };
166
- const onError = (error) => {
167
- cleanup();
168
- reject(error);
169
- };
170
- const cleanup = () => {
171
- child.off('spawn', onSpawn);
172
- child.off('error', onError);
173
- };
174
- child.once('spawn', onSpawn);
175
- child.once('error', onError);
176
- });
177
- }
@@ -1308,6 +1308,106 @@ export class RuntimeKernel {
1308
1308
  },
1309
1309
  ];
1310
1310
  }
1311
+ /** Stop one captured owner without cancelling other queued executions in its Session. */
1312
+ stopExecution(claim, input = {}) {
1313
+ normalizeStopSessionSource(input.source, input.workHubActionId);
1314
+ const execution = this.executionClaimStates.get(claim);
1315
+ if (!execution)
1316
+ throw new Error('Runtime execution claim belongs to another owner');
1317
+ if (execution.scopedStopAttempt)
1318
+ return execution.scopedStopAttempt;
1319
+ const run = execution.run;
1320
+ const active = run &&
1321
+ this.backendGenerationsFor(execution.sessionId).find((candidate) => candidate.activeRuns.get(run.runId) === run);
1322
+ if (!active && (execution.phase === 'released' || execution.phase === 'failed')) {
1323
+ return run
1324
+ ? this.retryStoppedRun({
1325
+ sessionId: execution.sessionId,
1326
+ runId: run.runId,
1327
+ turnId: run.turnId,
1328
+ }, input)
1329
+ : Promise.resolve();
1330
+ }
1331
+ if (active && run)
1332
+ this.assertScopedStopGeneration(active, run);
1333
+ // Validate first, then capture the capability synchronously. A pending
1334
+ // owner carries the stop through attach/reserve without a Session fence.
1335
+ execution.stopIntent ??= { input, claims: new Set([execution]) };
1336
+ if (active && run)
1337
+ this.captureScopedRunStop(active, run, input);
1338
+ else
1339
+ run?.stop(input.source, input.workHubActionId);
1340
+ execution.abortController.abort(execution.cancellation);
1341
+ const attempt = this.stopCapturedExecution(execution, input).finally(() => {
1342
+ if (execution.scopedStopAttempt === attempt)
1343
+ execution.scopedStopAttempt = undefined;
1344
+ });
1345
+ execution.scopedStopAttempt = attempt;
1346
+ return attempt;
1347
+ }
1348
+ /** A failed cleanup attempt keeps its captured owner parked until a successful retry. */
1349
+ waitForExecutionStop(claim) {
1350
+ const run = this.executionClaimStates.get(claim)?.run;
1351
+ const operation = run &&
1352
+ this.retainedRunStopOperation({
1353
+ sessionId: claim.sessionId,
1354
+ runId: run.runId,
1355
+ turnId: run.turnId,
1356
+ });
1357
+ return operation ? operation.completion : Promise.resolve();
1358
+ }
1359
+ /** Whether a retained stop operation still owns cleanup for this exact Run. */
1360
+ hasPendingRunStop(identity) {
1361
+ return this.retainedRunStopOperation(identity) !== undefined;
1362
+ }
1363
+ retainedRunStopOperation(identity) {
1364
+ const operation = this.stopOperations.get(identity.sessionId);
1365
+ return operation &&
1366
+ [...operation.targets.values()].some((target) => target.runs.get(identity.runId)?.turnId === identity.turnId)
1367
+ ? operation
1368
+ : undefined;
1369
+ }
1370
+ /** Exact identity lookup never redirects a completed Run's stop to its successor. */
1371
+ stopRun(identity, input = {}) {
1372
+ normalizeStopSessionSource(input.source, input.workHubActionId);
1373
+ const execution = [...(this.executionClaims.get(identity.sessionId) ?? [])].find((candidate) => candidate.run?.runId === identity.runId && candidate.run.turnId === identity.turnId);
1374
+ if (execution)
1375
+ return this.stopExecution(execution.handle, input);
1376
+ for (const active of this.backendGenerationsFor(identity.sessionId)) {
1377
+ const run = active.activeRuns.get(identity.runId);
1378
+ if (!run || run.turnId !== identity.turnId)
1379
+ continue;
1380
+ this.assertScopedStopGeneration(active, run);
1381
+ this.captureScopedRunStop(active, run, input);
1382
+ return this.retryStoppedRun(identity, input);
1383
+ }
1384
+ return this.retryStoppedRun(identity, input);
1385
+ }
1386
+ assertScopedStopGeneration(active, run) {
1387
+ if ([...active.activeRuns.values()].some((other) => other !== run && !other.isStopped())) {
1388
+ throw new Error('Cannot stop one Run while its backend generation owns another active Run');
1389
+ }
1390
+ }
1391
+ captureScopedRunStop(active, run, input) {
1392
+ const operation = this.claimRunForStop(active.sessionId, input, active, run);
1393
+ if (operation && active.phase === 'active')
1394
+ active.phase = 'stopping';
1395
+ }
1396
+ async stopCapturedExecution(execution, input) {
1397
+ await execution.settled;
1398
+ if (execution.run) {
1399
+ await this.retryStoppedRun({
1400
+ sessionId: execution.sessionId,
1401
+ runId: execution.run.runId,
1402
+ turnId: execution.run.turnId,
1403
+ }, input);
1404
+ }
1405
+ }
1406
+ async retryStoppedRun(identity, input) {
1407
+ const operation = this.retainedRunStopOperation(identity);
1408
+ if (operation)
1409
+ await this.enqueueStopOperation(identity.sessionId, operation, input, true);
1410
+ }
1311
1411
  stopSession(sessionId, input = {}) {
1312
1412
  normalizeStopSessionSource(input.source, input.workHubActionId);
1313
1413
  const existing = this.stopAttempts.get(sessionId);
@@ -1403,12 +1503,22 @@ export class RuntimeKernel {
1403
1503
  buildStopOperation(input) {
1404
1504
  const abortSource = normalizeStopSessionSource(input.source, input.workHubActionId);
1405
1505
  const ts = this.deps.now();
1506
+ let resolveCompletion;
1507
+ let rejectCompletion;
1508
+ const completion = new Promise((resolve, reject) => {
1509
+ resolveCompletion = resolve;
1510
+ rejectCompletion = reject;
1511
+ });
1512
+ void completion.catch(() => undefined);
1406
1513
  return {
1407
1514
  abortSource,
1408
1515
  ts,
1409
1516
  statusProjected: false,
1410
1517
  targets: new Map(),
1411
1518
  queue: Promise.resolve(),
1519
+ completion,
1520
+ resolveCompletion,
1521
+ rejectCompletion,
1412
1522
  };
1413
1523
  }
1414
1524
  enqueueStopOperation(sessionId, operation, input, deliverPending) {
@@ -1507,7 +1617,16 @@ export class RuntimeKernel {
1507
1617
  if (target.delivery.kind === 'failed')
1508
1618
  failures.add(target.delivery.error);
1509
1619
  }
1510
- failures.throwIfAny(`Stop cleanup failed for session ${sessionId}`);
1620
+ try {
1621
+ failures.throwIfAny(`Stop cleanup failed for session ${sessionId}`);
1622
+ if (completed)
1623
+ operation.resolveCompletion();
1624
+ }
1625
+ catch (error) {
1626
+ if (completed)
1627
+ operation.rejectCompletion(error);
1628
+ throw error;
1629
+ }
1511
1630
  }
1512
1631
  async respondToSandboxBoundary(sessionId, response) {
1513
1632
  const key = interactionOwnerKey(sessionId, response.requestId);
@@ -2038,7 +2157,9 @@ export class RuntimeKernel {
2038
2157
  releaseStoppedRunReferences(operation, run) {
2039
2158
  for (const target of operation.targets.values()) {
2040
2159
  const stoppedRun = target.runs.get(run.runId);
2041
- if (stoppedRun?.run === run)
2160
+ // A failed terminal append still needs this captured Run on retry, even
2161
+ // after its stream exits. Drop it only once stop settlement succeeded.
2162
+ if (stoppedRun?.run === run && stoppedRun.stopCompleted)
2042
2163
  stoppedRun.run = undefined;
2043
2164
  if (target.active &&
2044
2165
  target.delivery.kind !== 'pending' &&
@@ -2077,7 +2198,7 @@ export class RuntimeKernel {
2077
2198
  async clearBackendQuarantineForActivation(sessionId, execution) {
2078
2199
  const ownsCurrentStop = execution.phase === 'attached' &&
2079
2200
  execution.stopIntent !== undefined &&
2080
- this.stopIntents.get(sessionId) === execution.stopIntent;
2201
+ execution.stopIntent.claims.has(execution);
2081
2202
  if (this.stopOperations.has(sessionId) && !ownsCurrentStop) {
2082
2203
  throw new Error(`Session ${sessionId} is quarantined by a retained stop operation`);
2083
2204
  }
@@ -1698,9 +1698,28 @@ export class SessionManager {
1698
1698
  return await inFlight.promise;
1699
1699
  }
1700
1700
  const runtimeExecution = this.runtimeKernel.claimExecution(claim.targetSessionId);
1701
- const promise = this.enqueueClaimedAgentGraphIntent(resolved, runtimeExecution).finally(() => runtimeExecution.release());
1701
+ const owner = {
1702
+ identity: {
1703
+ sessionId: claim.targetSessionId,
1704
+ runId: claim.targetRunId,
1705
+ turnId: claim.targetTurnId,
1706
+ },
1707
+ execution: runtimeExecution,
1708
+ hostAdmitted: false,
1709
+ };
1710
+ resolved.onHostAdmission = () => {
1711
+ owner.hostAdmitted = true;
1712
+ };
1713
+ const promise = this.enqueueClaimedAgentGraphIntent(resolved, runtimeExecution, async () => {
1714
+ runtimeExecution.release();
1715
+ // Keep the existing Session slot until scoped backend cleanup completes.
1716
+ // Other queued claims retain their own uncancelled runtime capabilities.
1717
+ await owner.stopTask?.catch(() => undefined);
1718
+ await this.runtimeKernel.waitForExecutionStop?.(runtimeExecution);
1719
+ });
1702
1720
  this.claimedAgentGraphIntentRuns.set(claim.claimId, {
1703
1721
  requestFingerprint,
1722
+ owner,
1704
1723
  promise,
1705
1724
  });
1706
1725
  try {
@@ -1712,7 +1731,7 @@ export class SessionManager {
1712
1731
  }
1713
1732
  }
1714
1733
  }
1715
- enqueueClaimedAgentGraphIntent(input, runtimeExecution) {
1734
+ enqueueClaimedAgentGraphIntent(input, runtimeExecution, release) {
1716
1735
  const sessionId = input.claim.targetSessionId;
1717
1736
  const previous = this.claimedAgentGraphSessionTails.get(sessionId) ?? Promise.resolve();
1718
1737
  let enteredQueue = false;
@@ -1729,7 +1748,8 @@ export class SessionManager {
1729
1748
  }
1730
1749
  enteredQueue = true;
1731
1750
  return this.runClaimedAgentGraphIntentOnce(input, runtimeExecution);
1732
- });
1751
+ })
1752
+ .finally(release);
1733
1753
  const tail = queuedExecution.then(() => { }, () => { });
1734
1754
  this.claimedAgentGraphSessionTails.set(sessionId, tail);
1735
1755
  void tail.then(() => {
@@ -1742,8 +1762,10 @@ export class SessionManager {
1742
1762
  rejectStopped = reject;
1743
1763
  });
1744
1764
  const onRuntimeStop = () => {
1745
- if (!enteredQueue)
1765
+ if (!enteredQueue) {
1766
+ runtimeExecution.release();
1746
1767
  rejectStopped(runtimeExecution.stopSignal.reason);
1768
+ }
1747
1769
  };
1748
1770
  runtimeExecution.stopSignal.addEventListener('abort', onRuntimeStop, { once: true });
1749
1771
  if (runtimeExecution.stopSignal.aborted)
@@ -1804,6 +1826,9 @@ export class SessionManager {
1804
1826
  this.assertClaimedAgentGraphRun(child, snapshot, claim, run);
1805
1827
  if (input.hostedGraphExecution) {
1806
1828
  const admission = await this.requireClaimedGraphAdmissionIdentity(claim, input.hostedGraphExecution);
1829
+ if (input.hostedGraphExecution && runtimeExecution.stopSignal.aborted)
1830
+ throw runtimeExecution.stopSignal.reason;
1831
+ input.onHostAdmission?.();
1807
1832
  await this.consumeLinkedRootExecution({
1808
1833
  sessionId: child.id,
1809
1834
  turnId: claim.targetTurnId,
@@ -1839,13 +1864,22 @@ export class SessionManager {
1839
1864
  await this.finalizeChildWorkspacePatches(child.id);
1840
1865
  // An invocation is what makes a Turn exist on the ledger, so the run listing
1841
1866
  // is the whole occupancy check: a Turn with durable content has one.
1842
- const turnOwner = (await this.listInvocations(child.id)).find((candidate) => candidate.turnId === claim.targetTurnId);
1867
+ const invocations = await this.listInvocations(child.id);
1868
+ const turnOwner = invocations.find((candidate) => candidate.turnId === claim.targetTurnId);
1843
1869
  if (turnOwner) {
1844
1870
  throw new Error(`Claimed graph turn ${claim.targetTurnId} is already owned by run ${turnOwner.runId}`);
1845
1871
  }
1846
- if (child.isArchived || child.status === 'aborted') {
1872
+ if (child.isArchived) {
1847
1873
  throw new Error('Claimed graph execution target child session is terminated');
1848
1874
  }
1875
+ if (child.status === 'aborted') {
1876
+ const latest = [...invocations].sort((left, right) => right.openedAt - left.openedAt)[0];
1877
+ // A graph stop ends one activation, not the reusable operator. Only a
1878
+ // durable graph-supervisor stop permits a new claim on an aborted child.
1879
+ if (latest?.terminalEvent?.actions?.stateDelta?.abortSource !== 'graph.supervisor') {
1880
+ throw new Error('Claimed graph execution target child session is terminated');
1881
+ }
1882
+ }
1849
1883
  if (input.abortSignal?.aborted) {
1850
1884
  throw new Error('Claimed graph execution was cancelled before runtime admission');
1851
1885
  }
@@ -1860,11 +1894,28 @@ export class SessionManager {
1860
1894
  let aborted = false;
1861
1895
  let stopPromise;
1862
1896
  const userMessageId = await this.claimedGraphUserMessageId(claim, input.hostedGraphExecution);
1897
+ if (input.hostedGraphExecution && runtimeExecution.stopSignal.aborted)
1898
+ throw runtimeExecution.stopSignal.reason;
1899
+ // Host runs this gate in its Session admission lease immediately before
1900
+ // the durable admission. Until it passes, a graph stop only cancels the
1901
+ // local capability and the gate refuses the Turn; after it passes, the
1902
+ // stop must go through the Host fence.
1903
+ const hostedAdmitExecution = input.hostedGraphExecution
1904
+ ? async () => {
1905
+ if (runtimeExecution.stopSignal.aborted)
1906
+ return 'cancelled';
1907
+ const admission = admitExecution ? await admitExecution() : 'executing';
1908
+ if (admission === 'cancelled' || runtimeExecution.stopSignal.aborted)
1909
+ return 'cancelled';
1910
+ input.onHostAdmission?.();
1911
+ return 'executing';
1912
+ }
1913
+ : admitExecution;
1863
1914
  const execution = this.consumeLinkedRootExecution({
1864
1915
  ...identity,
1865
1916
  userMessageId,
1866
1917
  execution: rootExecution,
1867
- ...(admitExecution ? { admitExecution } : {}),
1918
+ ...(hostedAdmitExecution ? { admitExecution: hostedAdmitExecution } : {}),
1868
1919
  content: { text: input.prompt },
1869
1920
  start: ({ runId, userMessageId, onRunStarted }) => this.sendMessage(child.id, {
1870
1921
  turnId: claim.targetTurnId,
@@ -2478,6 +2529,61 @@ export class SessionManager {
2478
2529
  },
2479
2530
  };
2480
2531
  }
2532
+ /** Stop the captured graph activation, never a newer Run or a queued sibling. */
2533
+ async stopAgentGraphActivation(identity, input = { source: 'graph_supervisor' }) {
2534
+ const authority = isRuntimeHostedRootAuthority(this.deps.messageAuthority)
2535
+ ? this.deps.messageAuthority
2536
+ : undefined;
2537
+ // Until the Host admission gate passes, the capability is only local
2538
+ // ownership: cancel it synchronously, and both the pre-submission check
2539
+ // and that gate refuse the Turn. Once admitted, Host must commit its
2540
+ // durable fence before Runtime stop.
2541
+ if (authority) {
2542
+ const admission = await this.deps.hostedAgentGraphExecution?.readRootTurnAdmissionIdentity(identity.sessionId, identity.turnId);
2543
+ if (admission && admission.runId !== identity.runId) {
2544
+ throw new Error('Graph stop identity does not match its durable admission');
2545
+ }
2546
+ // A recovered local claim can be new while the Host already owns its Run.
2547
+ // Recheck the gate after the durable read closes that lookup race.
2548
+ if (admission || this.findGraphRuntimeActivation(identity)?.hostAdmitted) {
2549
+ await authority.stopRootRun(identity, input);
2550
+ return;
2551
+ }
2552
+ }
2553
+ await this.stopGraphRuntimeActivation(identity, input);
2554
+ }
2555
+ /** Whether a failed stop left cleanup retained for this exact graph activation. */
2556
+ hasPendingAgentGraphActivationStop(identity) {
2557
+ return this.runtimeKernel.hasPendingRunStop?.(identity) ?? false;
2558
+ }
2559
+ findGraphRuntimeActivation(identity) {
2560
+ return [...this.claimedAgentGraphIntentRuns.values()]
2561
+ .map((entry) => entry.owner)
2562
+ .find((candidate) => candidate.identity.sessionId === identity.sessionId &&
2563
+ candidate.identity.runId === identity.runId &&
2564
+ candidate.identity.turnId === identity.turnId);
2565
+ }
2566
+ stopGraphRuntimeActivation(identity, input) {
2567
+ const owner = this.findGraphRuntimeActivation(identity);
2568
+ if (owner) {
2569
+ if (owner.stopTask)
2570
+ return owner.stopTask;
2571
+ if (!this.runtimeKernel.stopExecution) {
2572
+ throw new Error('Runtime kernel does not support scoped graph activation stops');
2573
+ }
2574
+ const task = this.runtimeKernel.stopExecution(owner.execution, input);
2575
+ owner.stopTask = task;
2576
+ void task.catch(() => {
2577
+ if (owner.stopTask === task)
2578
+ owner.stopTask = undefined;
2579
+ });
2580
+ return task;
2581
+ }
2582
+ if (!this.runtimeKernel.stopRun) {
2583
+ throw new Error('Runtime kernel does not support exact Run stops');
2584
+ }
2585
+ return this.runtimeKernel.stopRun(identity, input);
2586
+ }
2481
2587
  async stopSession(sessionId, input = {}) {
2482
2588
  const hostedAuthority = isRuntimeHostedRootAuthority(this.deps.messageAuthority)
2483
2589
  ? this.deps.messageAuthority
@@ -2488,15 +2594,20 @@ export class SessionManager {
2488
2594
  ? hostedAuthority.stopSession(childSessionId, input)
2489
2595
  : this.runtimeKernel.stopSession(childSessionId, input));
2490
2596
  }
2491
- async deliverHostedRootStop(sessionId, input = {}) {
2597
+ async deliverHostedRootStop(sessionId, input = {}, identity) {
2598
+ if (identity && identity.sessionId !== sessionId) {
2599
+ throw new Error('Hosted stop identity belongs to another Session');
2600
+ }
2492
2601
  const authority = isRuntimeHostedRootAuthority(this.deps.messageAuthority)
2493
2602
  ? this.deps.messageAuthority
2494
2603
  : undefined;
2495
- await this.#stopSessionTree(sessionId, this.runtimeKernel.stopSession(sessionId, input), (childSessionId) => authority
2604
+ await this.#stopSessionTree(sessionId, identity
2605
+ ? this.stopGraphRuntimeActivation(identity, input)
2606
+ : this.runtimeKernel.stopSession(sessionId, input), (childSessionId) => authority
2496
2607
  ? authority.stopSession(childSessionId, input)
2497
- : this.runtimeKernel.stopSession(childSessionId, input));
2608
+ : this.runtimeKernel.stopSession(childSessionId, input), identity);
2498
2609
  }
2499
- async #stopSessionTree(sessionId, ownStop, stopChild) {
2610
+ async #stopSessionTree(sessionId, ownStop, stopChild, parentIdentity) {
2500
2611
  // Observe immediately while child lookup runs; await below still propagates the original error.
2501
2612
  void ownStop.catch(() => undefined);
2502
2613
  let childStops = [];
@@ -2504,7 +2615,9 @@ export class SessionManager {
2504
2615
  try {
2505
2616
  const children = await this.listChildSessions(sessionId);
2506
2617
  childStops = await Promise.allSettled(children
2507
- .filter((child) => child.subagentParent?.lifecycle === 'foreground')
2618
+ .filter((child) => child.subagentParent?.lifecycle === 'foreground' &&
2619
+ (!parentIdentity ||
2620
+ child.subagentParent.spawnedBy.parentTurnId === parentIdentity.turnId))
2508
2621
  .map((child) => stopChild(child.id)));
2509
2622
  }
2510
2623
  catch (error) {