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
@@ -101,6 +101,8 @@ const PROJECTION_FIELDS = [
101
101
  'thinkingLevel',
102
102
  'lastReadMessageId',
103
103
  'liveRunState',
104
+ 'backgroundActivity',
105
+ 'backgroundActivityVersion',
104
106
  ];
105
107
  export const SESSION_CATALOG_OPERATION_SPECS = {
106
108
  'session.shared.query': defineOperation({
@@ -176,7 +178,15 @@ function decodeSharedSessionCatalogQueryResult(value) {
176
178
  return { session };
177
179
  }
178
180
  export function decodeSharedSessionCatalogProjection(value) {
179
- const exact = requireShapedRecord(value, 'shared Session catalog projection', ['kind', 'id', 'revision', 'createdAt', 'activityAt', 'name', 'status'], ['lastMessageAt', 'lastMessagePreview', 'liveRunState', 'blockedReason', 'statusUpdatedAt']);
181
+ const exact = requireShapedRecord(value, 'shared Session catalog projection', ['kind', 'id', 'revision', 'createdAt', 'activityAt', 'name', 'status'], [
182
+ 'lastMessageAt',
183
+ 'lastMessagePreview',
184
+ 'liveRunState',
185
+ 'backgroundActivity',
186
+ 'backgroundActivityVersion',
187
+ 'blockedReason',
188
+ 'statusUpdatedAt',
189
+ ]);
180
190
  if (exact.kind !== 'shared_session')
181
191
  throw invalidProtocolFrame('Invalid shared Session kind');
182
192
  return {
@@ -190,6 +200,7 @@ export function decodeSharedSessionCatalogProjection(value) {
190
200
  ...optionalText(exact, 'lastMessagePreview', SESSION_CATALOG_PREVIEW_MAX_BYTES),
191
201
  status: decodeSessionStatus(exact.status),
192
202
  ...optionalLiveRunState(exact),
203
+ ...optionalBackgroundActivity(exact),
193
204
  ...optionalBlockedReason(exact),
194
205
  ...optionalTimestamp(exact, 'statusUpdatedAt'),
195
206
  };
@@ -518,6 +529,7 @@ export function decodeSessionCatalogProjection(value) {
518
529
  ...optionalText(record, 'lastMessagePreview', SESSION_CATALOG_PREVIEW_MAX_BYTES),
519
530
  status: decodeSessionStatus(record.status),
520
531
  ...optionalLiveRunState(record),
532
+ ...optionalBackgroundActivity(record),
521
533
  ...optionalBlockedReason(record),
522
534
  ...optionalTimestamp(record, 'statusUpdatedAt'),
523
535
  ...optionalEntityId(record, 'parentSessionId'),
@@ -640,6 +652,29 @@ function optionalBlockedReason(record) {
640
652
  }
641
653
  return { blockedReason: record.blockedReason };
642
654
  }
655
+ function optionalBackgroundActivity(record) {
656
+ const activity = record.backgroundActivity;
657
+ if (activity === undefined) {
658
+ if (record.backgroundActivityVersion !== undefined)
659
+ throw invalidProtocolFrame('Session background activity version requires activity');
660
+ return {};
661
+ }
662
+ if (activity !== 'idle' &&
663
+ activity !== 'running' &&
664
+ activity !== 'waiting_for_user' &&
665
+ activity !== 'blocked')
666
+ throw invalidProtocolFrame('Invalid Session background activity');
667
+ if (record.backgroundActivityVersion === undefined)
668
+ return { backgroundActivity: activity };
669
+ const version = requireExactRecord(record.backgroundActivityVersion, 'Session background activity version', ['hostGeneration', 'revision']);
670
+ return {
671
+ backgroundActivity: activity,
672
+ backgroundActivityVersion: {
673
+ hostGeneration: decodeHostGeneration(version.hostGeneration),
674
+ revision: requireCount(version.revision, 'Session background activity revision'),
675
+ },
676
+ };
677
+ }
643
678
  function optionalLiveRunState(record) {
644
679
  if (record.liveRunState === undefined)
645
680
  return {};
@@ -671,13 +706,6 @@ function optionalLiveRunState(record) {
671
706
  liveRunState.runEpoch < 0)) {
672
707
  throw invalidProtocolFrame('Invalid Session catalog run epoch');
673
708
  }
674
- if (liveRunState.hostGeneration !== undefined &&
675
- (typeof liveRunState.hostGeneration !== 'string' ||
676
- liveRunState.hostGeneration.length === 0 ||
677
- liveRunState.hostGeneration.length > SESSION_CATALOG_HOST_GENERATION_MAX_CHARS ||
678
- /[\u0000-\u001f\u007f]/.test(liveRunState.hostGeneration))) {
679
- throw invalidProtocolFrame('Invalid Session catalog host generation');
680
- }
681
709
  return {
682
710
  liveRunState: {
683
711
  schemaVersion: SESSION_CATALOG_LIVE_RUN_STATE_SCHEMA_VERSION,
@@ -685,10 +713,19 @@ function optionalLiveRunState(record) {
685
713
  ...(liveRunState.runEpoch === undefined ? {} : { runEpoch: liveRunState.runEpoch }),
686
714
  ...(liveRunState.hostGeneration === undefined
687
715
  ? {}
688
- : { hostGeneration: liveRunState.hostGeneration }),
716
+ : { hostGeneration: decodeHostGeneration(liveRunState.hostGeneration) }),
689
717
  },
690
718
  };
691
719
  }
720
+ function decodeHostGeneration(value) {
721
+ if (typeof value !== 'string' ||
722
+ value.length === 0 ||
723
+ value.length > SESSION_CATALOG_HOST_GENERATION_MAX_CHARS ||
724
+ /[\u0000-\u001f\u007f]/.test(value)) {
725
+ throw invalidProtocolFrame('Invalid Session catalog host generation');
726
+ }
727
+ return value;
728
+ }
692
729
  function optionalSubagent(record) {
693
730
  if (!Object.hasOwn(record, 'subagent'))
694
731
  return {};
@@ -33,44 +33,51 @@ export async function startInteractiveRuntimeHostCandidate(options, createCompos
33
33
  if (!ownership)
34
34
  return { kind: 'loser' };
35
35
  const { owner, managedConfig } = ownership;
36
- try {
37
- const composition = await createComposition(managedConfig);
38
- const loadedKernel = await kernelModule;
39
- if (loadedKernel.kind === 'failed')
40
- throw loadedKernel.error;
41
- const { RuntimeHostKernel } = loadedKernel.module;
42
- const websocket = managedConfig?.listeners.websocket;
43
- const accessAuthority = websocket
44
- ? await import('./access-authority.js').then(({ openRuntimeHostAccessAuthority }) => openRuntimeHostAccessAuthority(owner.controlDirectory))
45
- : undefined;
46
- const host = await RuntimeHostKernel.start({
47
- owner,
48
- lifecycleMode: 'ephemeral',
49
- initialConnectionTimeoutMs: options.initialConnectionTimeoutMs,
50
- idleGraceMs: options.idleGraceMs,
51
- handshakeTimeoutMs: options.handshakeTimeoutMs,
52
- generation: options.generation,
53
- composition,
54
- ...(options.initialClientAdmission
55
- ? { initialClientAdmission: options.initialClientAdmission }
56
- : {}),
57
- ...(accessAuthority ? { accessAuthority } : {}),
58
- ...(websocket && accessAuthority
59
- ? {
60
- listenerSetFactory: async (input) => {
61
- const { startRuntimeHostAuthenticatedListenerSet } = await import('./listener-set.js');
62
- return startRuntimeHostAuthenticatedListenerSet(input, {
63
- websocket: { ...websocket, accessAuthority },
64
- });
65
- },
66
- }
67
- : {}),
68
- });
69
- return { kind: 'winner', host };
70
- }
71
- catch (error) {
72
- if (!owner.closed)
73
- await owner.close();
74
- throw error;
75
- }
36
+ const prepared = await (async () => {
37
+ try {
38
+ const composition = await createComposition(managedConfig);
39
+ const loadedKernel = await kernelModule;
40
+ if (loadedKernel.kind === 'failed')
41
+ throw loadedKernel.error;
42
+ const websocket = managedConfig?.listeners.websocket;
43
+ // Keep this the last fallible step: once opened, the authority passes
44
+ // straight to Kernel.start, which owns its cleanup.
45
+ const accessAuthority = websocket
46
+ ? await import('./access-authority.js').then(({ openRuntimeHostAccessAuthority }) => openRuntimeHostAccessAuthority(owner.controlDirectory))
47
+ : undefined;
48
+ const kernelOptions = {
49
+ owner,
50
+ lifecycleMode: 'ephemeral',
51
+ initialConnectionTimeoutMs: options.initialConnectionTimeoutMs,
52
+ idleGraceMs: options.idleGraceMs,
53
+ handshakeTimeoutMs: options.handshakeTimeoutMs,
54
+ generation: options.generation,
55
+ composition,
56
+ ...(options.initialClientAdmission
57
+ ? { initialClientAdmission: options.initialClientAdmission }
58
+ : {}),
59
+ ...(accessAuthority ? { accessAuthority } : {}),
60
+ ...(websocket && accessAuthority
61
+ ? {
62
+ listenerSetFactory: async (input) => {
63
+ const { startRuntimeHostAuthenticatedListenerSet } = await import('./listener-set.js');
64
+ return startRuntimeHostAuthenticatedListenerSet(input, {
65
+ websocket: { ...websocket, accessAuthority },
66
+ });
67
+ },
68
+ }
69
+ : {}),
70
+ };
71
+ return { Kernel: loadedKernel.module.RuntimeHostKernel, options: kernelOptions };
72
+ }
73
+ catch (error) {
74
+ if (!owner.closed)
75
+ await owner.close();
76
+ throw error;
77
+ }
78
+ })();
79
+ // Kernel owns cleanup from here, including retaining the owner until process
80
+ // termination when startup cleanup exceeds its deadline.
81
+ const host = await prepared.Kernel.start(prepared.options);
82
+ return { kind: 'winner', host };
76
83
  }
@@ -150,7 +150,10 @@ import { HostRuntimePolicyCoordinator } from './runtime-policy-coordinator.js';
150
150
  import { startHostModelMetadataRefresh } from './model-metadata-refresh.js';
151
151
  import { HostRuntimeResourceCoordinator } from './runtime-resource-coordinator.js';
152
152
  import { SessionAdmissionGate } from './session-admission-gate.js';
153
+ import { workHubResultOrigin } from './workhub-result-coordinator.js';
153
154
  import { HostSessionCatalogCoordinator } from './session-catalog-coordinator.js';
155
+ import { SessionBackgroundActivityProjection } from './session-background-activity.js';
156
+ import { SessionInteractionActivityProjection } from './session-interaction-activity.js';
154
157
  import { HostWorkspaceResolver } from './workspace-resolver.js';
155
158
  import { HostSessionRetirementCoordinator } from './session-retirement-coordinator.js';
156
159
  import { HostStorageMaintenance } from './storage-maintenance.js';
@@ -592,6 +595,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
592
595
  let resolveAvailableToolNames;
593
596
  let resolveNewSessionToolNames;
594
597
  const hostChanges = new HostChangeFeed();
598
+ const backgroundActivity = new SessionBackgroundActivityProjection({
599
+ hostGeneration: context.hostEpoch,
600
+ graph: (sessionId) => graphCoordinator?.readSessionActivity(sessionId) ?? 'idle',
601
+ supervisor: (sessionId) => graphSupervisorWake?.readSessionActivity(sessionId) ?? 'idle',
602
+ publish: (sessionId) => hostChanges.publishSessionCatalog(sessionId),
603
+ });
595
604
  // Startup, once, in the background: the Host owns the model catalog, so it
596
605
  // is the one process that gets to ask models.dev what is true today. On any
597
606
  // failure the build's committed snapshot stands.
@@ -785,6 +794,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
785
794
  domainModuleDrainBegun = true;
786
795
  beginRuntimeHostDomainModuleDrain(domainModules);
787
796
  };
797
+ const interactionActivity = new SessionInteractionActivityProjection({
798
+ interactions: stores.interactionStore,
799
+ sandboxBoundaries: stores.sessionStore,
800
+ onChanged: (sessionId) => graphCoordinator?.refreshSessionInteractionActivity(sessionId),
801
+ onError: (sessionId, error) => console.warn('[runtime-host] Could not refresh Session interaction activity', sessionId, error),
802
+ });
788
803
  const interactions = new HostInteractionCoordinator({
789
804
  store: stores.interactionStore,
790
805
  sandboxBoundaries: stores.sessionStore,
@@ -794,6 +809,10 @@ export async function createExecutionRuntimeHostComposition(context, options = {
794
809
  interactions: interactionProjection,
795
810
  }),
796
811
  refreshCanonicalContinuity: async (sessionId, admission, attention) => {
812
+ // This also runs without an open Session subscription; sidebar activity
813
+ // must observe every canonical answer, withdrawal, and Run closure.
814
+ // The presentation refresh isolates failures so canonical work still runs.
815
+ await interactionActivity.refresh(sessionId);
797
816
  await continuityCoordinator.refreshCanonical(sessionId, admission, attention);
798
817
  sessionAdmission.detach(() => workHubResults?.notify(sessionId));
799
818
  },
@@ -936,6 +955,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
936
955
  bindRun: (identity) => messages.bindRun(identity),
937
956
  executeRoot: (input) => executeHostedExecutionToSettlement(requireRootCoordinator(rootCoordinator), input),
938
957
  stopRoot: (identity, input) => requireRootCoordinator(rootCoordinator).stopRoot(identity, input),
958
+ stopRootRun: (identity, input) => requireRootCoordinator(rootCoordinator).stopRootRun(identity, input),
939
959
  stopSession: (sessionId, input) => requireRootCoordinator(rootCoordinator).stopSession(sessionId, input),
940
960
  };
941
961
  const resolveInteractiveToolSurface = async (input) => {
@@ -1266,6 +1286,8 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1266
1286
  runtime: manager,
1267
1287
  newId: randomUUID,
1268
1288
  acquireResidency: () => context.acquireResidency('agent-graph'),
1289
+ readTurnPendingInteractionCount: (sessionId, turnId) => interactionActivity.readTurnPendingInteractionCount(sessionId, turnId),
1290
+ onSessionActivityChanged: (sessionId) => backgroundActivity.changed(sessionId),
1269
1291
  onReconciliation: (rootSessionId, result) => {
1270
1292
  void requireGraphSupervisorWake(graphSupervisorWake).notify(rootSessionId, result);
1271
1293
  },
@@ -1708,6 +1730,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1708
1730
  }
1709
1731
  },
1710
1732
  acquireResidency: () => context.acquireResidency('agent-graph-supervisor'),
1733
+ onSessionActivityChanged: (sessionId) => backgroundActivity.changed(sessionId),
1711
1734
  onError: () => context.requestDrain(),
1712
1735
  });
1713
1736
  const goalExecutionCoordinator = new HostGoalExecutionCoordinator({
@@ -1785,6 +1808,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1785
1808
  turnIndex: requireTranscriptReader(transcriptReader),
1786
1809
  runtimePolicy: runtimePolicyStores,
1787
1810
  manager,
1811
+ readBackgroundActivity: (sessionId) => backgroundActivity.snapshot(sessionId),
1788
1812
  admission: sessionAdmission,
1789
1813
  continuity: continuityCoordinator,
1790
1814
  workspaceResolver,
@@ -1846,6 +1870,36 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1846
1870
  return outcome.result.kind === 'committed' ? 'committed' : 'revision_conflict';
1847
1871
  },
1848
1872
  });
1873
+ /**
1874
+ * One delegation-retirement read for both consumers: the coordination
1875
+ * coordinator's own actions and the archive guard's relationship check.
1876
+ * A finished Turn retires the delegation long before anything removes its
1877
+ * ledger row, so "live" must come from the execution, not the ledger.
1878
+ */
1879
+ const readWorkHubDelegationRetirement = async (assignment, admission) => {
1880
+ const disposition = admission
1881
+ ? await messages.readMessageExecutionDispositionAdmitted(assignment.targetSessionId, assignment.targetMessageId, admission)
1882
+ : await messages.readMessageExecutionDisposition(assignment.targetSessionId, assignment.targetMessageId);
1883
+ if (disposition.kind === 'recovering')
1884
+ return 'recovering';
1885
+ if (disposition.kind === 'pending')
1886
+ return 'not_retired';
1887
+ if (disposition.kind === 'cancelled' || disposition.kind === 'shared_turn') {
1888
+ return 'retired';
1889
+ }
1890
+ const identity = {
1891
+ sessionId: assignment.targetSessionId,
1892
+ turnId: disposition.turnId,
1893
+ runId: disposition.runId,
1894
+ };
1895
+ const latest = await coordinator.readLatestRootTurnLineage(identity);
1896
+ if (isActiveWorkHubRoot(coordinator, latest))
1897
+ return 'not_retired';
1898
+ // The same restart window as `stopOwnedWorkHubRoot`: an unregistered
1899
+ // root is not evidence that its work ended.
1900
+ const snapshot = await coordinator.read(latest);
1901
+ return isHostedExecutionTerminal(snapshot) ? 'retired' : 'recovering';
1902
+ };
1849
1903
  workHubCoordination = new HostWorkHubCoordinationCoordinator({
1850
1904
  routingModel: dependencies.workHubRoutingModel ?? createJevRoutingModel({ stores: runtimePolicyStores }),
1851
1905
  requestForm: (input) => interactions.requestForm(input),
@@ -1858,30 +1912,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1858
1912
  continuity: continuityCoordinator,
1859
1913
  executions: coordinator,
1860
1914
  sessionActions: {
1861
- readDelegationRetirement: async (assignment, admission) => {
1862
- const disposition = admission
1863
- ? await messages.readMessageExecutionDispositionAdmitted(assignment.targetSessionId, assignment.targetMessageId, admission)
1864
- : await messages.readMessageExecutionDisposition(assignment.targetSessionId, assignment.targetMessageId);
1865
- if (disposition.kind === 'recovering')
1866
- return 'recovering';
1867
- if (disposition.kind === 'pending')
1868
- return 'not_retired';
1869
- if (disposition.kind === 'cancelled' || disposition.kind === 'shared_turn') {
1870
- return 'retired';
1871
- }
1872
- const identity = {
1873
- sessionId: assignment.targetSessionId,
1874
- turnId: disposition.turnId,
1875
- runId: disposition.runId,
1876
- };
1877
- const latest = await coordinator.readLatestRootTurnLineage(identity);
1878
- if (isActiveWorkHubRoot(coordinator, latest))
1879
- return 'not_retired';
1880
- // The same restart window as `stopOwnedWorkHubRoot`: an unregistered
1881
- // root is not evidence that its work ended.
1882
- const snapshot = await coordinator.read(latest);
1883
- return isHostedExecutionTerminal(snapshot) ? 'retired' : 'recovering';
1884
- },
1915
+ readDelegationRetirement: readWorkHubDelegationRetirement,
1885
1916
  // Resolve and resume only the execution lineage owned by this
1886
1917
  // delegation. A Session-wide latest-failure query could otherwise
1887
1918
  // continue unrelated work started directly in the same Session.
@@ -2244,6 +2275,21 @@ export async function createExecutionRuntimeHostComposition(context, options = {
2244
2275
  root: coordinator,
2245
2276
  messages,
2246
2277
  interactions,
2278
+ workHub: {
2279
+ readDelegationRetirement: (assignment, admission) => readWorkHubDelegationRetirement(assignment, admission),
2280
+ hasUndeliveredResult: async (assignment, admission) => {
2281
+ if (!workHubResults || !assignment.returnResults)
2282
+ return false;
2283
+ // Same observation delivery is keyed on; the transcript content is
2284
+ // not needed to identify the result event.
2285
+ const observed = await workHubResults.inspect(assignment, admission, false);
2286
+ if (!observed)
2287
+ return false;
2288
+ // Root admission is the delivery receipt (see startWorkHubResult).
2289
+ const receipt = await stores.agentRunStore.readRootTurnAdmission(WORKHUB_COORDINATION_SESSION_ID, workHubResultOrigin(assignment, observed).eventId);
2290
+ return !receipt;
2291
+ },
2292
+ },
2247
2293
  goals: requireGoal(goal),
2248
2294
  scheduledTasks,
2249
2295
  resources: runtimeResources,
@@ -50,6 +50,7 @@ export async function startExecutionRuntimeHostService(options, dependencies = {
50
50
  let peerEndpointOwner;
51
51
  let peerMesh;
52
52
  let host;
53
+ let kernelOwnsRoot = false;
53
54
  try {
54
55
  if (options.peer) {
55
56
  peerEndpointOwner = await openRuntimeHostPeerEndpointOwner({
@@ -88,6 +89,9 @@ export async function startExecutionRuntimeHostService(options, dependencies = {
88
89
  });
89
90
  }
90
91
  const accessAuthority = await openRuntimeHostAccessAuthority(owner.controlDirectory);
92
+ // Kernel owns the root from here, including retaining it until process
93
+ // termination when startup or shutdown cleanup exceeds its deadline.
94
+ kernelOwnsRoot = true;
91
95
  host = await RuntimeHostKernel.start({
92
96
  owner,
93
97
  lifecycleMode: 'service',
@@ -127,7 +131,7 @@ export async function startExecutionRuntimeHostService(options, dependencies = {
127
131
  await host?.close().catch(() => undefined);
128
132
  await peerMesh?.close().catch(() => undefined);
129
133
  await peerEndpointOwner?.close().catch(() => undefined);
130
- if (!owner.closed)
134
+ if (!kernelOwnsRoot && !owner.closed)
131
135
  await owner.close();
132
136
  throw error;
133
137
  }
@@ -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
  }
@@ -2358,8 +2394,8 @@ export class RootTurnCoordinator {
2358
2394
  throw new RuntimeMessageAuthorityInvariantError('Fresh follow-up root Turn did not reserve execution');
2359
2395
  }
2360
2396
  }
2361
- async deliverRuntimeStopIntent(sessionId, input = { source: 'stop_button' }) {
2362
- await this.manager.deliverHostedRootStop(sessionId, input);
2397
+ async deliverRuntimeStopIntent(sessionId, input = { source: 'stop_button' }, identity) {
2398
+ await this.manager.deliverHostedRootStop(sessionId, input, identity);
2363
2399
  }
2364
2400
  async stopActiveTurn(sessionId, active) {
2365
2401
  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
+ }