maka-agent 0.2.0-dev.25.20260908 → 0.2.0-dev.27.20260910

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 (110) hide show
  1. package/dist/cli-core.js +21 -0
  2. package/dist/mcp-capability-provider.js +4 -1
  3. package/dist/pi-tui-mcp-status.js +2 -2
  4. package/dist/pi-tui-pickers.js +19 -29
  5. package/dist/runtime-host-cli.js +43 -3
  6. package/dist/runtime-host-handoff-surface.js +10 -8
  7. package/dist/runtime-host-lifecycle-transaction.js +28 -3
  8. package/dist/runtime-host-local-source-retirement.js +1 -1
  9. package/dist/runtime-host-setup-command.js +29 -6
  10. package/dist/runtime-host-update-command.js +49 -5
  11. package/dist/session-export-command.js +72 -0
  12. package/dist/tui-autocomplete-layout.js +3 -1
  13. package/dist/tui-copy-catalog.js +6 -3
  14. package/dist/tui-editor-render.js +36 -0
  15. package/dist/tui-mcp-control.js +41 -6
  16. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  17. package/node_modules/@maka/core/dist/runtime-event.js +3 -0
  18. package/node_modules/@maka/core/dist/session.js +29 -4
  19. package/node_modules/@maka/core/dist/usage-stats/types.js +2 -0
  20. package/node_modules/@maka/core/dist/workhub-action-result.js +68 -0
  21. package/node_modules/@maka/core/dist/workhub-routing.js +126 -0
  22. package/node_modules/@maka/core/package.json +3 -3
  23. package/node_modules/@maka/eval/dist/toolchain-verification.js +1 -1
  24. package/node_modules/@maka/mcp/dist/form-elicitation.js +213 -0
  25. package/node_modules/@maka/mcp/dist/index.js +337 -71
  26. package/node_modules/@maka/runtime/dist/agent-run.js +10 -1
  27. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +7 -3
  28. package/node_modules/@maka/runtime/dist/builtin-tools.js +21 -2
  29. package/node_modules/@maka/runtime/dist/goal-continuation.js +5 -1
  30. package/node_modules/@maka/runtime/dist/plugin-agent-service.js +131 -0
  31. package/node_modules/@maka/runtime/dist/plugin-approval-service.js +33 -0
  32. package/node_modules/@maka/runtime/dist/plugin-attachment-service.js +53 -0
  33. package/node_modules/@maka/runtime/dist/plugin-command-service.js +100 -0
  34. package/node_modules/@maka/runtime/dist/plugin-data-services.js +332 -0
  35. package/node_modules/@maka/runtime/dist/plugin-fs-service.js +62 -0
  36. package/node_modules/@maka/runtime/dist/plugin-goal-service.js +61 -0
  37. package/node_modules/@maka/runtime/dist/plugin-invocation-signal.js +24 -0
  38. package/node_modules/@maka/runtime/dist/plugin-llm-service.js +85 -0
  39. package/node_modules/@maka/runtime/dist/plugin-lsp-service.js +94 -0
  40. package/node_modules/@maka/runtime/dist/plugin-scope-registry.js +91 -0
  41. package/node_modules/@maka/runtime/dist/plugin-session-query-service.js +71 -0
  42. package/node_modules/@maka/runtime/dist/plugin-shell-env-service.js +87 -0
  43. package/node_modules/@maka/runtime/dist/plugin-shell-service.js +74 -0
  44. package/node_modules/@maka/runtime/dist/plugin-skill-service.js +93 -0
  45. package/node_modules/@maka/runtime/dist/plugin-system-prompt-service.js +346 -0
  46. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +18 -52
  47. package/node_modules/@maka/runtime/dist/plugin-user-question-service.js +43 -0
  48. package/node_modules/@maka/runtime/dist/plugin-web-service.js +69 -0
  49. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +20 -1
  50. package/node_modules/@maka/runtime/dist/runtime-kernel.js +120 -13
  51. package/node_modules/@maka/runtime/dist/session-export.js +177 -0
  52. package/node_modules/@maka/runtime/dist/session-manager.js +20 -36
  53. package/node_modules/@maka/runtime/package.json +18 -0
  54. package/node_modules/@maka/runtime-host/dist/client/connection.js +30 -5
  55. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +83 -18
  56. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +46 -12
  57. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +4 -2
  58. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +18 -1
  59. package/node_modules/@maka/runtime-host/dist/operator/setup-frame.js +31 -21
  60. package/node_modules/@maka/runtime-host/dist/protocol/index.js +13 -1
  61. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +3 -2
  62. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +30 -5
  63. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +1 -0
  64. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +90 -188
  65. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +4 -0
  66. package/node_modules/@maka/runtime-host/dist/server/canonical-session-projection.js +2 -1
  67. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +62 -4
  68. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +28 -8
  69. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +112 -56
  70. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +497 -27
  71. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +74 -0
  72. package/node_modules/@maka/runtime-host/dist/server/failure-diagnostic.js +24 -0
  73. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +7 -3
  74. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -3
  75. package/node_modules/@maka/runtime-host/dist/server/host-session-availability.js +5 -2
  76. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +4 -3
  77. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +64 -4
  78. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +83 -17
  79. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +25 -4
  80. package/node_modules/@maka/runtime-host/dist/server/operation-dispatcher.js +2 -7
  81. package/node_modules/@maka/runtime-host/dist/server/plugin-data-runtime.js +234 -0
  82. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  83. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +12 -0
  84. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +289 -96
  85. package/node_modules/@maka/runtime-host/dist/server/runtime-resource-coordinator.js +11 -8
  86. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +31 -21
  87. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +1 -1
  88. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +20 -8
  89. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +15 -104
  90. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +3 -0
  91. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +85 -117
  92. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +201 -136
  93. package/node_modules/@maka/storage/dist/agent-run-store.js +60 -3
  94. package/node_modules/@maka/storage/dist/artifact-store.js +40 -3
  95. package/node_modules/@maka/storage/dist/atomic-file-write.js +74 -0
  96. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +13 -6
  97. package/node_modules/@maka/storage/dist/credential-store.js +12 -63
  98. package/node_modules/@maka/storage/dist/execution-stores.js +5 -2
  99. package/node_modules/@maka/storage/dist/mcp-config-store.js +10 -25
  100. package/node_modules/@maka/storage/dist/session-bundle-policy.js +333 -30
  101. package/node_modules/@maka/storage/dist/session-store.js +16 -4
  102. package/node_modules/@maka/storage/dist/settings-store.js +8 -4
  103. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +11 -0
  104. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +12 -1
  105. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +79 -8
  106. package/node_modules/@maka/storage/dist/stable-storage.js +14 -1
  107. package/node_modules/@maka/storage/package.json +2 -0
  108. package/package.json +1 -1
  109. package/node_modules/@maka/core/dist/workhub-creation-intent.js +0 -990
  110. package/node_modules/@maka/core/dist/workhub-session-resolver.js +0 -50
@@ -53,13 +53,27 @@ export function isContinuationStartRuntimeEvent(event) {
53
53
  return (event.actions?.stateDelta?.continuationStart === true ||
54
54
  event.actions?.continuationStart !== undefined);
55
55
  }
56
+ export function projectRuntimeEventCoordinationReceipt(event) {
57
+ if (!event.actions?.coordination)
58
+ return undefined;
59
+ return {
60
+ type: 'workhub_coordination',
61
+ kind: 'action_receipt',
62
+ schemaVersion: 1,
63
+ id: event.id,
64
+ turnId: event.turnId,
65
+ ts: event.ts,
66
+ receipt: event.actions.coordination,
67
+ };
68
+ }
56
69
  /**
57
70
  * Whether the event can affect the StoredMessage projection or the state needed
58
71
  * to construct one. Pure control-plane facts are intentionally absent so a
59
72
  * transcript reader can stream past them without retaining the whole ledger.
60
73
  */
61
74
  export function affectsRuntimeEventStoredMessageProjection(event) {
62
- return (event.content !== undefined ||
75
+ return (event.actions?.coordination !== undefined ||
76
+ event.content !== undefined ||
63
77
  isTerminalRuntimeEvent(event) ||
64
78
  event.actions?.permissionRequest !== undefined ||
65
79
  event.actions?.permissionDecision !== undefined ||
@@ -143,6 +157,11 @@ export function projectRuntimeEventsToStoredMessages(events, options) {
143
157
  break;
144
158
  }
145
159
  }
160
+ const coordinationReceipt = projectRuntimeEventCoordinationReceipt(event);
161
+ if (coordinationReceipt) {
162
+ messages.push(coordinationReceipt);
163
+ projected = true;
164
+ }
146
165
  if (event.actions?.permissionRequest) {
147
166
  const request = event.actions.permissionRequest;
148
167
  state.permissionRequestById.set(request.requestId, {
@@ -530,6 +530,111 @@ export class RuntimeKernel {
530
530
  runId: continuation.runId,
531
531
  }, options, () => this.revalidateContinuationSafety(continuation), inheritedSandboxBoundaryDenied);
532
532
  }
533
+ /** Host coordination uses the same Run owner and terminal authority without a provider send. */
534
+ async *runCoordinationOperation(sessionId, input, options, execute) {
535
+ const execution = this.takeExecutionClaim(sessionId);
536
+ execution.hostOperation = true;
537
+ try {
538
+ await this.enterExecutionClaim(execution);
539
+ const header = await this.deps.store.readHeader(sessionId);
540
+ const run = new AgentRun({
541
+ sessionId,
542
+ header,
543
+ userInput: input,
544
+ runId: options.runId,
545
+ userMessageId: options.userMessageId,
546
+ durability: 'required',
547
+ runStore: this.deps.runStore,
548
+ runtimeEventStore: this.deps.runtimeEventStore,
549
+ newId: this.deps.newId,
550
+ now: this.deps.now,
551
+ effectiveOrchestration: resolveEffectiveOrchestration('default', undefined),
552
+ hooks: {
553
+ reserveRun: async (id, nextHeader, activeRun) => {
554
+ const active = await this.reserveParentRun(id, nextHeader, activeRun, execution);
555
+ this.reserveExecutionClaim(execution, active, activeRun);
556
+ return active;
557
+ },
558
+ unregisterRun: (active, activeRun) => this.unregisterParentRun(active, activeRun),
559
+ updateHeader: (id, patch) => this.updateHeader(id, patch),
560
+ updateStatus: (id, status, reason, ts) => this.updateStatus(id, status, reason, ts),
561
+ ...this.messageProjectionHook(),
562
+ },
563
+ });
564
+ this.attachExecutionClaim(execution, run);
565
+ const owners = this.createRunOwnerScope(run, execution);
566
+ try {
567
+ owners.bindMessage(this.deps.messageAuthority, {
568
+ sessionId,
569
+ turnId: input.turnId,
570
+ runId: run.runId,
571
+ });
572
+ // Keep the execution claim attached until finalization. Stop/drain can
573
+ // therefore cancel and await this Run without a provider generation.
574
+ await run.beginCoordination();
575
+ await options.onRunStarted?.(run.runId, header);
576
+ }
577
+ catch (error) {
578
+ await this.finalizeFailedRunStart(owners, run, execution, error);
579
+ return;
580
+ }
581
+ try {
582
+ if (run.isStopped())
583
+ return;
584
+ const executed = await execute();
585
+ const receipt = {
586
+ ...executed,
587
+ result: executed.result.disposition === 'clarify'
588
+ ? { ...executed.result, coordinationTurnId: input.turnId }
589
+ : executed.result,
590
+ };
591
+ const receiptEvent = {
592
+ id: this.deps.newId(),
593
+ sessionId,
594
+ turnId: input.turnId,
595
+ runId: run.runId,
596
+ invocationId: run.runId,
597
+ ts: this.deps.now(),
598
+ partial: false,
599
+ role: 'system',
600
+ author: 'host',
601
+ modelVisibility: 'hidden',
602
+ actions: { coordination: receipt },
603
+ };
604
+ await run.recordRuntimeEvents([receiptEvent], { requireDurableWrite: true });
605
+ if (run.isStopped())
606
+ return;
607
+ const complete = {
608
+ type: 'complete',
609
+ id: this.deps.newId(),
610
+ turnId: input.turnId,
611
+ ts: this.deps.now(),
612
+ stopReason: 'end_turn',
613
+ };
614
+ await run.acceptMappedEvent(complete, mapSessionEventToRuntimeEvent(complete, this.runtimeEventMapContext({
615
+ sessionId,
616
+ invocationId: run.runId,
617
+ runId: run.runId,
618
+ turnId: input.turnId,
619
+ })), { requireTerminalWrite: true });
620
+ yield complete;
621
+ }
622
+ catch (error) {
623
+ await run.recordFailure(error);
624
+ throw error;
625
+ }
626
+ finally {
627
+ const failures = new FailureCollector();
628
+ await failures.capture(() => owners.finalize());
629
+ await failures.capture(() => owners.releaseMessage());
630
+ failures.throwIfAny(`Coordination cleanup failed for ${run.runId}`);
631
+ }
632
+ }
633
+ finally {
634
+ this.releaseExecutionClaim(execution);
635
+ await this.flushBackendInvalidation(sessionId);
636
+ }
637
+ }
533
638
  async *compactSession(sessionId, input = {}) {
534
639
  const execution = this.takeExecutionClaim(sessionId);
535
640
  try {
@@ -1455,24 +1560,26 @@ export class RuntimeKernel {
1455
1560
  const generations = this.backendGenerationsFor(sessionId);
1456
1561
  await Promise.all(generations.map((active) => active.backend.respondToUserQuestion?.(response)));
1457
1562
  }
1563
+ activeRunsFor(sessionId) {
1564
+ const runs = new Set();
1565
+ for (const active of this.backendGenerationsFor(sessionId)) {
1566
+ for (const run of active.activeRuns.values())
1567
+ runs.add(run);
1568
+ }
1569
+ for (const claim of this.executionClaims.get(sessionId) ?? []) {
1570
+ if (claim.hostOperation && claim.run)
1571
+ runs.add(claim.run);
1572
+ }
1573
+ return [...runs];
1574
+ }
1458
1575
  hasActiveRuns(sessionId) {
1459
- return this.backendGenerationsFor(sessionId).some((active) => active.activeRuns.size > 0);
1576
+ return this.activeRunsFor(sessionId).length > 0;
1460
1577
  }
1461
1578
  runningTurnIds(sessionId) {
1462
- const turnIds = [];
1463
- for (const active of this.backendGenerationsFor(sessionId)) {
1464
- for (const run of active.activeRuns.values()) {
1465
- if (!turnIds.includes(run.turnId))
1466
- turnIds.push(run.turnId);
1467
- }
1468
- }
1469
- return turnIds;
1579
+ return [...new Set(this.activeRunsFor(sessionId).map((run) => run.turnId))];
1470
1580
  }
1471
1581
  hasActiveRun(sessionId, runId, turnId) {
1472
- return this.backendGenerationsFor(sessionId).some((active) => {
1473
- const run = active.activeRuns.get(runId);
1474
- return run !== undefined && (turnId === undefined || run.turnId === turnId);
1475
- });
1582
+ return this.activeRunsFor(sessionId).some((run) => run.runId === runId && (turnId === undefined || run.turnId === turnId));
1476
1583
  }
1477
1584
  requestRunHandoff(sessionId, runId, pause, signal) {
1478
1585
  if (!this.deps.inspectContinuationSafety)
@@ -0,0 +1,177 @@
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
+ * Export one Session, and the subagent subtree under it, as a portable bundle.
21
+ *
22
+ * The preparation is `exportSessionBundleState()` in `@maka/storage`, which
23
+ * already takes a consistent database snapshot, keeps writers out, filters the
24
+ * copy down to the exported Sessions, carries the context-offload closure, and
25
+ * proves the result with `PRAGMA foreign_key_check`. This module is the thin
26
+ * part: point it at a workspace, ask for a quiescent Session, and seal what
27
+ * comes back with the bundle codec.
28
+ *
29
+ * What it adds on top is the manifest — the Sessions carried, the schema
30
+ * versions the SOURCE database registers, and the connection by slug and model
31
+ * so an importer can resolve it locally. No credential is carried: the state
32
+ * allow-list in the export policy decides what is copied, and configuration is
33
+ * not on it.
34
+ */
35
+ import { mkdir, mkdtemp, rm, stat } from 'node:fs/promises';
36
+ import { join } from 'node:path';
37
+ import { tmpdir } from 'node:os';
38
+ import { SessionBundleFileError, } from '@maka/storage/session-bundle-contract';
39
+ import { createSessionBundleFileService } from '@maka/storage/session-bundle-file-service';
40
+ import { exportSessionBundleState, SessionBundleExportError, SESSION_BUNDLE_OMITTED_EVENT_TYPES, } from '@maka/storage/session-bundle-policy';
41
+ export const SESSION_EXPORT_MEDIA_TYPE = 'application/vnd.maka.session-export+json;version=1';
42
+ /** Generous by design; the codec is what enforces them. */
43
+ export const SESSION_EXPORT_BUNDLE_LIMITS = {
44
+ maxCompressedBytes: 2 * 1024 ** 3,
45
+ maxDecompressedTarBytes: 8 * 1024 ** 3,
46
+ maxPayloadBytes: 8 * 1024 ** 3,
47
+ maxFileBytes: 2 * 1024 ** 3,
48
+ maxEntryCount: 1_000_000,
49
+ maxManifestBytes: 4 * 1024 ** 2,
50
+ maxStateIdentityBytes: 4 * 1024 ** 2,
51
+ maxPathBytes: 4096,
52
+ maxPathDepth: 32,
53
+ };
54
+ export async function exportSessionBundle(input) {
55
+ if (!(await isDirectory(input.workspaceRoot))) {
56
+ return {
57
+ ok: false,
58
+ reason: { kind: 'workspace_not_found', workspaceRoot: input.workspaceRoot },
59
+ };
60
+ }
61
+ if (await exists(input.destination)) {
62
+ return { ok: false, reason: { kind: 'destination_exists' } };
63
+ }
64
+ const staging = await mkdtemp(join(tmpdir(), 'maka-session-export-'));
65
+ try {
66
+ const stateRoot = join(staging, 'state');
67
+ const workspaceRoot = join(staging, 'workspace');
68
+ // The codec seals a state tree beside a workspace tree. A Session's own
69
+ // files are the state; the user's project directory is not part of the
70
+ // conversation and is deliberately absent.
71
+ await mkdir(workspaceRoot, { recursive: true });
72
+ let plan;
73
+ try {
74
+ plan = await exportSessionBundleState({
75
+ stateRoot: input.workspaceRoot,
76
+ // Maka's desktop layout keeps state and configuration in one directory,
77
+ // so these are shared on purpose. Configuration stays out of the bundle
78
+ // because the policy copies an allow-list of state entries, not because
79
+ // the roots are apart.
80
+ configRoot: input.workspaceRoot,
81
+ allowShared: true,
82
+ destinationRoot: stateRoot,
83
+ sessionId: input.sessionId,
84
+ requireQuiescent: true,
85
+ includeSubtree: true,
86
+ omitDiagnostics: true,
87
+ });
88
+ }
89
+ catch (error) {
90
+ const failure = asExportFailure(error, input.workspaceRoot);
91
+ if (failure)
92
+ return { ok: false, reason: failure };
93
+ throw error;
94
+ }
95
+ const manifest = {
96
+ format: 'maka.session-export',
97
+ formatVersion: 1,
98
+ exportedAt: (input.now ?? Date.now)(),
99
+ rootSessionId: plan.sessionId,
100
+ sessionIds: plan.sessionIds,
101
+ schema: plan.sourceSchema,
102
+ connection: plan.connection,
103
+ includedEntries: plan.includedEntries,
104
+ excludedEntries: plan.excludedEntries,
105
+ diagnosticsOmitted: true,
106
+ omittedEventTypes: SESSION_BUNDLE_OMITTED_EVENT_TYPES,
107
+ };
108
+ const stateIdentity = {
109
+ mediaType: SESSION_EXPORT_MEDIA_TYPE,
110
+ bytes: Buffer.from(`${JSON.stringify(manifest)}\n`, 'utf8'),
111
+ };
112
+ const artifact = await createSessionBundleFileService().pack({
113
+ snapshot: { stateRoot, workspaceRoot, stateIdentity },
114
+ envelope: { sessionId: plan.sessionId },
115
+ destination: input.destination,
116
+ limits: input.limits ?? SESSION_EXPORT_BUNDLE_LIMITS,
117
+ });
118
+ return { ok: true, artifact, export: manifest };
119
+ }
120
+ catch (error) {
121
+ if (error instanceof SessionBundleFileError) {
122
+ if (error.details?.quota !== undefined) {
123
+ return { ok: false, reason: { kind: 'bundle_limit', details: error.details } };
124
+ }
125
+ // The precheck fails fast, but the packer publishes atomically and can
126
+ // still lose the race. Reporting that as a generic IO failure would give
127
+ // a caller a different exit code for the same outcome.
128
+ if (error.code === 'destination_exists') {
129
+ return { ok: false, reason: { kind: 'destination_exists' } };
130
+ }
131
+ return { ok: false, reason: { kind: 'io_failed', message: error.message } };
132
+ }
133
+ const failure = asExportFailure(error, input.workspaceRoot);
134
+ if (failure)
135
+ return { ok: false, reason: failure };
136
+ return { ok: false, reason: { kind: 'io_failed', message: String(error) } };
137
+ }
138
+ finally {
139
+ await rm(staging, { recursive: true, force: true }).catch(() => { });
140
+ }
141
+ }
142
+ function asExportFailure(error, workspaceRoot) {
143
+ if (!(error instanceof SessionBundleExportError))
144
+ return undefined;
145
+ switch (error.code) {
146
+ case 'session_active':
147
+ return { kind: 'session_active', message: error.message };
148
+ case 'schema_unsupported':
149
+ return { kind: 'schema_unsupported', message: error.message };
150
+ case 'symlink':
151
+ case 'path_escape':
152
+ case 'unsupported_entry':
153
+ return { kind: 'artifact_unsafe', message: error.message };
154
+ case 'missing_entry':
155
+ return { kind: 'artifact_missing', message: error.message };
156
+ case 'invalid_root':
157
+ // The policy reports a missing Session through this code too, and only
158
+ // the message separates it from a directory that is not a workspace.
159
+ return /session does not exist/i.test(error.message)
160
+ ? { kind: 'session_not_found' }
161
+ : { kind: 'workspace_not_found', workspaceRoot };
162
+ case 'destination_not_empty':
163
+ return { kind: 'destination_exists' };
164
+ default:
165
+ return { kind: 'io_failed', message: error.message };
166
+ }
167
+ }
168
+ async function isDirectory(path) {
169
+ return stat(path)
170
+ .then((metadata) => metadata.isDirectory())
171
+ .catch(() => false);
172
+ }
173
+ async function exists(path) {
174
+ return stat(path)
175
+ .then(() => true)
176
+ .catch(() => false);
177
+ }
@@ -16,17 +16,6 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- /**
20
- * SessionManager — the public Runtime API.
21
- *
22
- * Ties together:
23
- * SessionStore (storage) — SQLite persistence
24
- * AgentBackend (AiSdkBackend etc) — SDK adapter
25
- * ExecutionBoundary — session sandbox authority
26
- *
27
- * `SessionStore` comes from `@maka/storage`; its public interface owns
28
- * persistence and same-session serialization semantics.
29
- */
30
19
  import { createHash } from 'node:crypto';
31
20
  import { isDeepStrictEqual } from 'node:util';
32
21
  import { setTimeout as delay } from 'node:timers/promises';
@@ -1280,6 +1269,9 @@ export class SessionManager {
1280
1269
  // Operational telemetry must never alter resume correctness.
1281
1270
  }
1282
1271
  }
1272
+ runCoordinationOperation(sessionId, input, options, execute) {
1273
+ return this.runtimeKernel.runCoordinationOperation(sessionId, input, options, execute);
1274
+ }
1283
1275
  async *compactSession(sessionId, input = {}) {
1284
1276
  yield* this.runtimeKernel.compactSession(sessionId, input);
1285
1277
  }
@@ -2314,43 +2306,30 @@ export class SessionManager {
2314
2306
  const hostedAuthority = isRuntimeHostedRootAuthority(this.deps.messageAuthority)
2315
2307
  ? this.deps.messageAuthority
2316
2308
  : undefined;
2317
- const ownStop = hostedAuthority
2309
+ await this.#stopSessionTree(sessionId, hostedAuthority
2318
2310
  ? hostedAuthority.stopSession(sessionId, input)
2319
- : this.runtimeKernel.stopSession(sessionId, input);
2320
- let childStops = [];
2321
- let childLookupError;
2322
- try {
2323
- const children = await this.listChildSessions(sessionId);
2324
- childStops = await Promise.allSettled(children
2325
- .filter((child) => child.subagentParent?.lifecycle === 'foreground')
2326
- .map((child) => hostedAuthority
2327
- ? hostedAuthority.stopSession(child.id, input)
2328
- : this.runtimeKernel.stopSession(child.id, input)));
2329
- }
2330
- catch (error) {
2331
- childLookupError = error;
2332
- }
2333
- await ownStop;
2334
- const childStopError = childStops.find((result) => result.status === 'rejected')?.reason;
2335
- if (childLookupError !== undefined)
2336
- throw childLookupError;
2337
- if (childStopError !== undefined)
2338
- throw childStopError;
2311
+ : this.runtimeKernel.stopSession(sessionId, input), (childSessionId) => hostedAuthority
2312
+ ? hostedAuthority.stopSession(childSessionId, input)
2313
+ : this.runtimeKernel.stopSession(childSessionId, input));
2339
2314
  }
2340
2315
  async deliverHostedRootStop(sessionId, input = {}) {
2341
- const ownStop = this.runtimeKernel.stopSession(sessionId, input);
2342
2316
  const authority = isRuntimeHostedRootAuthority(this.deps.messageAuthority)
2343
2317
  ? this.deps.messageAuthority
2344
2318
  : undefined;
2319
+ await this.#stopSessionTree(sessionId, this.runtimeKernel.stopSession(sessionId, input), (childSessionId) => authority
2320
+ ? authority.stopSession(childSessionId, input)
2321
+ : this.runtimeKernel.stopSession(childSessionId, input));
2322
+ }
2323
+ async #stopSessionTree(sessionId, ownStop, stopChild) {
2324
+ // Observe immediately while child lookup runs; await below still propagates the original error.
2325
+ void ownStop.catch(() => undefined);
2345
2326
  let childStops = [];
2346
2327
  let childLookupError;
2347
2328
  try {
2348
2329
  const children = await this.listChildSessions(sessionId);
2349
2330
  childStops = await Promise.allSettled(children
2350
2331
  .filter((child) => child.subagentParent?.lifecycle === 'foreground')
2351
- .map((child) => authority
2352
- ? authority.stopSession(child.id, input)
2353
- : this.runtimeKernel.stopSession(child.id, input)));
2332
+ .map((child) => stopChild(child.id)));
2354
2333
  }
2355
2334
  catch (error) {
2356
2335
  childLookupError = error;
@@ -2385,6 +2364,11 @@ export class SessionManager {
2385
2364
  goalId: input.execution.goalId,
2386
2365
  };
2387
2366
  }
2367
+ else if (input.execution.kind === 'workhub_coordination' &&
2368
+ input.execution.operation === 'action') {
2369
+ recoveryReason = 'coordination_action_admission_without_run';
2370
+ diagnostic = { executionKind: input.execution.kind, operation: input.execution.operation };
2371
+ }
2388
2372
  else if (input.execution.kind === 'legacy_automation') {
2389
2373
  root = { kind: 'legacy_automation', legacyAutomationId: input.execution.automationId };
2390
2374
  recoveryReason = 'legacy_automation_authority_removed';
@@ -76,8 +76,25 @@
76
76
  "./plan-mode": "./dist/plan-mode.js",
77
77
  "./plan-tools": "./dist/plan-tools.js",
78
78
  "./plugin-composition-loader": "./dist/plugin-composition-loader.js",
79
+ "./plugin-command-service": "./dist/plugin-command-service.js",
80
+ "./plugin-data-services": "./dist/plugin-data-services.js",
81
+ "./plugin-goal-service": "./dist/plugin-goal-service.js",
82
+ "./plugin-lsp-service": "./dist/plugin-lsp-service.js",
83
+ "./plugin-session-query-service": "./dist/plugin-session-query-service.js",
84
+ "./plugin-shell-env-service": "./dist/plugin-shell-env-service.js",
85
+ "./plugin-skill-service": "./dist/plugin-skill-service.js",
86
+ "./plugin-agent-service": "./dist/plugin-agent-service.js",
87
+ "./plugin-attachment-service": "./dist/plugin-attachment-service.js",
88
+ "./plugin-approval-service": "./dist/plugin-approval-service.js",
89
+ "./plugin-fs-service": "./dist/plugin-fs-service.js",
79
90
  "./plugin-kernel": "./dist/plugin-kernel.js",
91
+ "./plugin-llm-service": "./dist/plugin-llm-service.js",
80
92
  "./plugin-runtime": "./dist/plugin-runtime.js",
93
+ "./plugin-scope-registry": "./dist/plugin-scope-registry.js",
94
+ "./plugin-system-prompt-service": "./dist/plugin-system-prompt-service.js",
95
+ "./plugin-shell-service": "./dist/plugin-shell-service.js",
96
+ "./plugin-user-question-service": "./dist/plugin-user-question-service.js",
97
+ "./plugin-web-service": "./dist/plugin-web-service.js",
81
98
  "./plugin-tool-service": "./dist/plugin-tool-service.js",
82
99
  "./process-tree-terminator": "./dist/process-tree-terminator.js",
83
100
  "./provider-request-telemetry": "./dist/provider-request-telemetry.js",
@@ -88,6 +105,7 @@
88
105
  "./sandbox-boundary-tool": "./dist/sandbox-boundary-tool.js",
89
106
  "./scheduled-task-tools": "./dist/scheduled-task-tools.js",
90
107
  "./session-recap": "./dist/session-recap.js",
108
+ "./session-export": "./dist/session-export.js",
91
109
  "./session-trace-projection": "./dist/session-trace-projection.js",
92
110
  "./shell-detect": "./dist/shell-detect.js",
93
111
  "./shell-run-contract": "./dist/shell-run-contract.js",
@@ -78,6 +78,12 @@ export class RuntimeHostRequestInterruptedError extends Error {
78
78
  this.retryable = mode === 'query';
79
79
  }
80
80
  }
81
+ // A Host response can reach the Client before the Host's transport write
82
+ // promise resumes and retires that request. Leave one slot free so replacing
83
+ // the observed response cannot transiently cross the Host's hard limit. The
84
+ // Host serializes outbound writes, so at most one response occupies this
85
+ // acknowledgement window.
86
+ const CLIENT_MAX_IN_FLIGHT_DOMAIN_REQUESTS = RUNTIME_HOST_MAX_IN_FLIGHT_DOMAIN_REQUESTS - 1;
81
87
  class RuntimeHostConnectionImpl {
82
88
  cooperativeHandoff;
83
89
  rootId;
@@ -212,7 +218,7 @@ class RuntimeHostConnectionImpl {
212
218
  }
213
219
  #drainDomainRequests() {
214
220
  while (!this.#terminalError &&
215
- this.#inFlightDomainRequests < RUNTIME_HOST_MAX_IN_FLIGHT_DOMAIN_REQUESTS) {
221
+ this.#inFlightDomainRequests < CLIENT_MAX_IN_FLIGHT_DOMAIN_REQUESTS) {
216
222
  const queued = this.#queuedDomainFrames.shift();
217
223
  if (!queued)
218
224
  return;
@@ -243,9 +249,28 @@ class RuntimeHostConnectionImpl {
243
249
  }
244
250
  return status;
245
251
  }
246
- openSessionSubscription(input, timeoutMs) {
252
+ async openSessionSubscription(input, timeoutMs) {
253
+ const deadline = Date.now() + (timeoutMs === undefined ? 30_000 : requireTimeout(timeoutMs, 'timeoutMs'));
254
+ for (;;) {
255
+ try {
256
+ return await this.#openSessionSubscription(input, Math.max(1, deadline - Date.now()), timeoutMs);
257
+ }
258
+ catch (error) {
259
+ if (!(error instanceof RuntimeHostOperationError) ||
260
+ error.code !== 'transcript_preparing' ||
261
+ input.transcript.kind !== 'tail' ||
262
+ this.#terminalError ||
263
+ Date.now() >= deadline)
264
+ throw error;
265
+ // Each refusal committed a bounded, resumable index batch. Keep the
266
+ // caller in its loading state and yield before requesting more work.
267
+ await new Promise((resolve) => setTimeout(resolve, 25));
268
+ }
269
+ }
270
+ }
271
+ #openSessionSubscription(input, openTimeoutMs, requestTimeoutMs) {
247
272
  const expectedSessionId = input.sessionId;
248
- return this.#requestOperation('subscription.open', input, timeoutMs, (result) => {
273
+ return this.#requestOperation('subscription.open', input, openTimeoutMs, (result) => {
249
274
  if (result.hostEpoch !== this.hostEpoch) {
250
275
  throw new RuntimeHostSubscriptionError('host_epoch_changed', 'Session subscription opened for a different Host Epoch');
251
276
  }
@@ -255,9 +280,9 @@ class RuntimeHostConnectionImpl {
255
280
  if (this.#subscriptions.has(result.subscriptionId)) {
256
281
  throw new RuntimeHostSubscriptionError('correlation_changed', 'Runtime Host returned a duplicate subscription identity');
257
282
  }
258
- const subscription = new ClientSessionSubscription(result, () => this.#closeSessionSubscription(result.subscriptionId), (query) => this.request('session.transcript.page', query, timeoutMs), async () => {
283
+ const subscription = new ClientSessionSubscription(result, () => this.#closeSessionSubscription(result.subscriptionId), (query) => this.request('session.transcript.page', query, requestTimeoutMs), async () => {
259
284
  try {
260
- await this.request('session.transcript.overlay.release', { subscriptionId: result.subscriptionId }, timeoutMs);
285
+ await this.request('session.transcript.overlay.release', { subscriptionId: result.subscriptionId }, requestTimeoutMs);
261
286
  }
262
287
  catch (error) {
263
288
  this.#fail(asError(error));