maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907

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 (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. package/package.json +1 -1
@@ -0,0 +1,273 @@
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 { randomUUID } from 'node:crypto';
20
+ import { isHostActivityIdle } from '../protocol/host-status.js';
21
+ import { RuntimeHostPermanentReconnectError } from './reconnect-lifecycle.js';
22
+ import { formatHostHandoff } from './host-handoff-copy.js';
23
+ import { redactSecrets } from '@maka/core/redaction';
24
+ export class HostHandoffCancelledError extends RuntimeHostPermanentReconnectError {
25
+ code = 'runtime_host_handoff_cancelled';
26
+ constructor() {
27
+ super('Runtime Host handoff was cancelled');
28
+ this.name = 'HostHandoffCancelledError';
29
+ }
30
+ }
31
+ /** Noninteractive callers receive the same decision instead of prompting or silently stopping work. */
32
+ export class HostHandoffRequiredError extends RuntimeHostPermanentReconnectError {
33
+ view;
34
+ code = 'runtime_host_handoff_required';
35
+ constructor(view) {
36
+ const copy = formatHostHandoff(view, 'en');
37
+ super([copy.title, copy.description, copy.detail, view.diagnostic].filter(Boolean).join('\n'));
38
+ this.view = view;
39
+ this.name = 'HostHandoffRequiredError';
40
+ }
41
+ }
42
+ /** One live attempt; persisted deployment transactions remain the sole recovery authority. */
43
+ export async function runHostHandoff(input) {
44
+ const interval = input.pollIntervalMs ?? 1_000;
45
+ if (!Number.isFinite(interval) || interval <= 0)
46
+ throw new RangeError('Invalid handoff observation interval');
47
+ let surface;
48
+ let view;
49
+ let signature;
50
+ let choice;
51
+ let wake;
52
+ let attemptAbort;
53
+ let cancelled = false;
54
+ // Admission can refuse an apparently idle snapshot. Do not turn that race
55
+ // (or a broken successor) into an automatic replacement storm.
56
+ const attempted = new Set();
57
+ let automaticAttempts = 0;
58
+ let recovery;
59
+ const publish = (next) => {
60
+ view = next;
61
+ surface?.update(next);
62
+ };
63
+ const submit = (revision, action) => {
64
+ if (!view || revision !== view.revision || !view.actions.includes(action))
65
+ return;
66
+ if (view.state === 'progress') {
67
+ if (action !== 'cancel' || cancelled)
68
+ return;
69
+ cancelled = true;
70
+ attemptAbort?.abort(new HostHandoffCancelledError());
71
+ publish({ ...view, revision: randomUUID(), actions: [] });
72
+ return;
73
+ }
74
+ if (choice)
75
+ return;
76
+ choice = { revision, action };
77
+ wake?.();
78
+ };
79
+ try {
80
+ for (;;) {
81
+ input.signal?.throwIfAborted();
82
+ if (cancelled)
83
+ throw new HostHandoffCancelledError();
84
+ if (choice?.action === 'cancel')
85
+ throw new HostHandoffCancelledError();
86
+ // Every action, including an explicit interruption, gets a fresh observation.
87
+ // Final identity/admission fencing is still the mutation adapter's responsibility.
88
+ let observed;
89
+ try {
90
+ observed = await input.observe(input.signal);
91
+ }
92
+ catch (error) {
93
+ input.signal?.throwIfAborted();
94
+ if (!view)
95
+ throw error;
96
+ // Lost observation is not permission to reuse the last mutation capability.
97
+ // Keep this journey visible and retry without chaining a fatal dialog.
98
+ observed = {
99
+ kind: 'blocked',
100
+ blocker: {
101
+ identity: JSON.stringify(['unavailable', view.target]),
102
+ target: view.target,
103
+ reason: 'unavailable',
104
+ mayExitNaturally: false,
105
+ diagnostic: boundedDiagnostic(error),
106
+ },
107
+ };
108
+ }
109
+ if (observed.kind === 'ready') {
110
+ if (input.signal?.aborted ||
111
+ choice?.action === 'cancel') {
112
+ await observed.value.close();
113
+ input.signal?.throwIfAborted();
114
+ throw new HostHandoffCancelledError();
115
+ }
116
+ return observed.value;
117
+ }
118
+ input.signal?.throwIfAborted();
119
+ // Cancellation belongs to the attempt, not to the observed Host. A new
120
+ // epoch or newly idle snapshot must not erase a click made during observe.
121
+ if (choice?.action === 'cancel') {
122
+ throw new HostHandoffCancelledError();
123
+ }
124
+ const blocker = observed.blocker;
125
+ if (recovery?.identity !== blocker.identity)
126
+ recovery = undefined;
127
+ const nextSignature = blockerSignature(blocker);
128
+ if (signature !== nextSignature) {
129
+ signature = nextSignature;
130
+ choice = undefined;
131
+ publish(projectBlocker(blocker, randomUUID(), recovery?.diagnostic));
132
+ }
133
+ const current = view;
134
+ const selected = choice;
135
+ choice = undefined;
136
+ if (selected?.action === 'cancel')
137
+ throw new HostHandoffCancelledError();
138
+ const cooperative = blocker.target.location === 'local' &&
139
+ blocker.activity?.cooperativeHandoff === true &&
140
+ blocker.activity.connections === 0 &&
141
+ blocker.activity.activeOperations === 0;
142
+ const automatic = !recovery &&
143
+ automaticAttempts < 3 &&
144
+ !attempted.has(nextSignature) &&
145
+ blocker.replacement?.canReplaceIdle &&
146
+ blocker.activity &&
147
+ (isHostActivityIdle(blocker.activity) || cooperative);
148
+ const interrupt = selected?.revision === current.revision && selected.action === 'interrupt';
149
+ const retry = selected?.revision === current.revision && selected.action === 'retry';
150
+ if ((automatic || interrupt || (retry && blocker.replacement?.canReplaceIdle)) &&
151
+ blocker.replacement) {
152
+ if (automatic) {
153
+ attempted.add(nextSignature);
154
+ automaticAttempts += 1;
155
+ }
156
+ attemptAbort = new AbortController();
157
+ const operationSignal = input.signal
158
+ ? AbortSignal.any([input.signal, attemptAbort.signal])
159
+ : attemptAbort.signal;
160
+ const progress = (phase) => publish({
161
+ ...current,
162
+ revision: randomUUID(),
163
+ state: 'progress',
164
+ phase: cooperative && !interrupt && phase === 'retiring' ? 'pausing' : phase,
165
+ actions: cancelled ? [] : ['cancel'],
166
+ });
167
+ if (input.openSurface)
168
+ surface ??= input.openSurface(submit);
169
+ progress(cooperative && !interrupt ? 'pausing' : 'checking');
170
+ // Do not abandon an irreversible cutover when the Surface closes. Its
171
+ // transaction settles (or persists recovery) before cancellation is observed.
172
+ let result;
173
+ try {
174
+ result = await blocker.replacement.execute(interrupt ? 'interrupt_active_work' : 'refuse_active_work', progress, automatic && !retry && !interrupt ? 'automatic' : 'explicit', operationSignal);
175
+ }
176
+ catch (error) {
177
+ result = { kind: 'recovery_required', diagnostic: boundedDiagnostic(error) };
178
+ }
179
+ finally {
180
+ attemptAbort = undefined;
181
+ }
182
+ recovery =
183
+ result.kind === 'recovery_required'
184
+ ? { identity: blocker.identity, diagnostic: result.diagnostic.slice(0, 8_192) }
185
+ : undefined;
186
+ // A completed attempt is not proof of readiness; observe the successor.
187
+ signature = undefined;
188
+ continue;
189
+ }
190
+ if (selected?.action === 'retry') {
191
+ // Explicit retry permits another safe probe, never an implicit interruption.
192
+ attempted.delete(nextSignature);
193
+ automaticAttempts = 0;
194
+ recovery = undefined;
195
+ signature = undefined;
196
+ continue;
197
+ }
198
+ const attention = projectBlocker(blocker, current.revision, recovery?.diagnostic);
199
+ if (!input.openSurface)
200
+ throw new HostHandoffRequiredError(attention);
201
+ surface ??= input.openSurface(submit);
202
+ publish(attention);
203
+ await new Promise((resolve, reject) => {
204
+ const finish = (error) => {
205
+ clearTimeout(timer);
206
+ input.signal?.removeEventListener('abort', abort);
207
+ wake = undefined;
208
+ if (error !== undefined)
209
+ reject(error);
210
+ else
211
+ resolve();
212
+ };
213
+ const abort = () => finish(input.signal?.reason);
214
+ const timer = setTimeout(finish, interval);
215
+ wake = () => finish();
216
+ input.signal?.addEventListener('abort', abort, { once: true });
217
+ if (input.signal?.aborted)
218
+ abort();
219
+ else if (choice)
220
+ finish();
221
+ });
222
+ }
223
+ }
224
+ finally {
225
+ surface?.close();
226
+ }
227
+ }
228
+ function projectBlocker(blocker, revision, recovery) {
229
+ const replacement = blocker.replacement;
230
+ return {
231
+ revision,
232
+ target: blocker.target,
233
+ state: 'attention',
234
+ reason: blocker.reason === 'unavailable'
235
+ ? 'retry_required'
236
+ : recovery || blocker.reason === 'repair'
237
+ ? 'repair_required'
238
+ : !replacement
239
+ ? 'operator_required'
240
+ : !blocker.activity
241
+ ? 'activity_unknown'
242
+ : isHostActivityIdle(blocker.activity)
243
+ ? 'retry_required'
244
+ : 'busy',
245
+ ...(blocker.activity ? { activity: blocker.activity } : {}),
246
+ mayExitNaturally: blocker.mayExitNaturally,
247
+ ...(replacement ? { operation: replacement.kind } : {}),
248
+ actions: replacement?.canInterrupt ? ['cancel', 'retry', 'interrupt'] : ['cancel', 'retry'],
249
+ defaultAction: 'cancel',
250
+ ...(blocker.operatorStep ? { operatorStep: blocker.operatorStep } : {}),
251
+ ...((recovery ?? blocker.diagnostic)
252
+ ? { diagnostic: redactSecrets((recovery ?? blocker.diagnostic)).slice(0, 8_192) }
253
+ : {}),
254
+ };
255
+ }
256
+ function blockerSignature(blocker) {
257
+ const { processUptimeSeconds: _uptime, ...activity } = blocker.activity ?? {};
258
+ return JSON.stringify([
259
+ blocker.identity,
260
+ blocker.target,
261
+ blocker.reason,
262
+ activity,
263
+ blocker.mayExitNaturally,
264
+ blocker.replacement?.kind,
265
+ blocker.replacement?.canReplaceIdle,
266
+ blocker.replacement?.canInterrupt,
267
+ blocker.operatorStep,
268
+ blocker.diagnostic,
269
+ ]);
270
+ }
271
+ function boundedDiagnostic(error) {
272
+ return redactSecrets(error instanceof Error ? error.message : String(error)).slice(0, 8_192);
273
+ }
@@ -23,9 +23,30 @@
23
23
  * transport detail here so lifecycle owners can model the operation as
24
24
  * retirement instead of spreading update-specific authority.
25
25
  */
26
- export function prepareConnectedRuntimeHostRetirement(connection, mode, timeoutMs) {
27
- return connection.request('host.upgrade.prepare', {
28
- expectedHostEpoch: connection.hostEpoch,
29
- allowInterruptActiveTasks: mode === 'interrupt_active_work',
30
- }, timeoutMs);
26
+ export async function prepareConnectedRuntimeHostRetirement(connection, mode, timeoutMs, signal) {
27
+ signal?.throwIfAborted();
28
+ // Retirement uses a dedicated lifecycle connection. Closing it cancels the
29
+ // Host's reversible preparation; a committed retirement remains committed.
30
+ const cancel = () => {
31
+ void connection.close().catch(() => undefined);
32
+ };
33
+ signal?.addEventListener('abort', cancel, { once: true });
34
+ try {
35
+ return await connection.request('host.upgrade.prepare', {
36
+ expectedHostEpoch: connection.hostEpoch,
37
+ allowInterruptActiveTasks: mode === 'interrupt_active_work',
38
+ ...(mode === 'refuse_active_work' && connection.cooperativeHandoff
39
+ ? { allowCooperativeHandoff: true }
40
+ : {}),
41
+ }, timeoutMs);
42
+ }
43
+ catch (error) {
44
+ // Cancellation is not an unavailable protocol: lifecycle fallback must
45
+ // never turn this deliberate disconnect into supervisor interruption.
46
+ signal?.throwIfAborted();
47
+ throw error;
48
+ }
49
+ finally {
50
+ signal?.removeEventListener('abort', cancel);
51
+ }
31
52
  }
@@ -16,12 +16,14 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ export * from './host-handoff.js';
20
+ export { formatHostHandoff } from './host-handoff-copy.js';
19
21
  export { RuntimeHostManagedActivationError, activateRuntimeHostManagedDeployment, } from './managed-activation.js';
20
22
  export { decodeRuntimeHostWebRtcStunPolicy, resolveRuntimeHostWebRtcStunUrls, } from '../webrtc-stun-policy.js';
21
23
  export { openRuntimeHostManagedStdioBridge } from './managed-stdio-bridge.js';
22
24
  export { connectRuntimeHost, connectExistingRuntimeHost, connectRemoteRuntimeHost, RuntimeHostOperationError, RuntimeHostRequestInterruptedError, } from './connection.js';
23
25
  export { prepareConnectedRuntimeHostRetirement, } from './host-retirement.js';
24
- export { forceTerminateObservedRegisteredRuntimeHost, forceTerminateRegisteredRuntimeHost, } from './registered-host-termination.js';
26
+ export { forceTerminateObservedRegisteredRuntimeHost, } from './registered-host-termination.js';
25
27
  export { LOCAL_RUNTIME_HOST_PROFILE, RUNTIME_HOST_ACCESS_CREDENTIAL_MAX_BYTES, createClientRuntimeHostCredentialStore, createClientRuntimeHostProfileCatalog, createFileRuntimeHostProfileCatalog, createRuntimeHostCapabilityProviderCredentialStore, createRuntimeHostProfileCredentialStore, connectRuntimeHostProfile, sameEnvironmentRuntimeHostDeployment, connectRemoteRuntimeHostProfile, decodeEnvironmentRuntimeHostProfile, decodePersistedRuntimeHostProfile, decodeRemoteRuntimeHostProfile, migrateRuntimeHostProfileOperatorCommand, remoteRuntimeHostUnavailableError, runtimeHostProfileAccess, runtimeHostProfileTargetFingerprint, sameRemoteRuntimeHostProfileTarget, sameResolvedRuntimeHostProfileTarget, subscribeClientRuntimeHostProfileCatalogChanges, RuntimeHostProfileConnectionError, } from './host-profile.js';
26
28
  export { createRuntimeHostReconnectingConnection, isRuntimeHostReconnectingConnection, } from './reconnecting-connection.js';
27
29
  export { RuntimeHostSshOperatorActivationError, activateRuntimeHostSshOperator, runtimeHostSshOperatorRemoteCommand, } from './ssh-operator-activation.js';
@@ -32,6 +32,9 @@ export function launchDetachedRuntimeHostCandidate(input) {
32
32
  const startupFailure = readStartupFailure(exited, startupAttemptId);
33
33
  const spawned = spawnedPid(child).then(({ pid }) => {
34
34
  child.unref();
35
+ // The guard observes launcher death; its IPC channel must not prevent
36
+ // that launcher from exiting naturally after its own work has finished.
37
+ child.channel?.unref();
35
38
  return { pid, startupAttemptId, exited, startupFailure };
36
39
  });
37
40
  return { spawned };
@@ -126,6 +126,9 @@ class RuntimeHostPeerClientImpl {
126
126
  if (this.#routeResolver === resolver)
127
127
  return () => undefined;
128
128
  this.#routeResolver = resolver;
129
+ for (const peerId of this.#endpoint?.connectivitySnapshot.connectedPeerIds ?? []) {
130
+ this.#notifyPeerConnected(peerId);
131
+ }
129
132
  for (const peerId of this.#routeListeners.keys()) {
130
133
  this.#subscribeResolver(peerId);
131
134
  this.#notifyRouteChange(peerId);
@@ -511,6 +514,8 @@ class RuntimeHostPeerClientImpl {
511
514
  for (const peerId of new Set([...previousPeers, ...nextPeers])) {
512
515
  if (previousPeers.has(peerId) !== nextPeers.has(peerId))
513
516
  this.#notifyRouteChange(peerId);
517
+ if (!previousPeers.has(peerId) && nextPeers.has(peerId))
518
+ this.#notifyPeerConnected(peerId);
514
519
  }
515
520
  }
516
521
  }
@@ -522,6 +527,14 @@ class RuntimeHostPeerClientImpl {
522
527
  this.#finishConsumer('mesh', this.#terminalError);
523
528
  }
524
529
  }
530
+ #notifyPeerConnected(peerId) {
531
+ try {
532
+ this.#routeResolver?.peerConnected?.(peerId);
533
+ }
534
+ catch {
535
+ // Mesh recovery must not interrupt the transport's connectivity watcher.
536
+ }
537
+ }
525
538
  async #drainInbound(endpoint) {
526
539
  try {
527
540
  while (true) {
@@ -16,16 +16,10 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { terminateProcessTree } from '@maka/runtime/process-tree-terminator';
20
19
  import { prepareStorageRootControlDirectory, resolveStorageRoot, } from '@maka/storage/root-authority';
21
20
  import { readHostRegistration } from '../control/registration.js';
22
21
  import { readRuntimeHostProcessIdentity, } from './process-identity.js';
23
22
  const TERMINATION_SETTLE_MS = 2_000;
24
- const defaultDependencies = {
25
- terminateProcess: terminateProcessTree,
26
- isProcessAlive,
27
- settleMs: TERMINATION_SETTLE_MS,
28
- };
29
23
  const defaultObservedDependencies = {
30
24
  isProcessAlive,
31
25
  readProcessIdentity: readRuntimeHostProcessIdentity,
@@ -38,53 +32,6 @@ const defaultObservedDependencies = {
38
32
  * the expected State Root. Callers must reserve this for explicit recovery
39
33
  * and keep their authorization current until the signal is sent.
40
34
  */
41
- export function forceTerminateRegisteredRuntimeHost(identity, stillOwnsProcess) {
42
- return forceTerminateRegisteredRuntimeHostWithDependencies(identity, stillOwnsProcess, defaultDependencies);
43
- }
44
- export async function forceTerminateRegisteredRuntimeHostWithDependencies(identity, stillOwnsProcess, dependencies) {
45
- if (!stillOwnsProcess())
46
- return false;
47
- const capability = await resolveStorageRoot({ path: identity.rootPath, kind: 'interactive' });
48
- if (capability.rootId !== identity.rootId)
49
- return false;
50
- const { controlDirectory } = await prepareStorageRootControlDirectory(capability);
51
- const registered = await readHostRegistration(controlDirectory);
52
- if (!registered)
53
- return true;
54
- if (!matchesIdentity(registered, identity))
55
- return false;
56
- if (!dependencies.isProcessAlive(identity.pid))
57
- return true;
58
- let signalTarget = registered;
59
- const signaled = await dependencies.terminateProcess({
60
- pid: identity.pid,
61
- signal: 'SIGKILL',
62
- hasExited: () => !dependencies.isProcessAlive(identity.pid),
63
- beforeSignal: async () => {
64
- // This runs after asynchronous process-tree discovery and immediately
65
- // before the OS signal, so neither a successor nor a reused PID can
66
- // inherit stale intent.
67
- signalTarget = await readHostRegistration(controlDirectory);
68
- return matchesIdentity(signalTarget, identity) && stillOwnsProcess();
69
- },
70
- fallback: () => {
71
- try {
72
- process.kill(identity.pid, 'SIGKILL');
73
- return true;
74
- }
75
- catch {
76
- return false;
77
- }
78
- },
79
- });
80
- if (!signalTarget)
81
- return true;
82
- if (!matchesIdentity(signalTarget, identity))
83
- return false;
84
- if (!signaled && dependencies.isProcessAlive(identity.pid))
85
- return false;
86
- return waitForExit(identity.pid, dependencies);
87
- }
88
35
  /**
89
36
  * Stops an ephemeral Host that Desktop did not launch in this process. Unlike
90
37
  * the owned-process path above, its authority is limited to the exact root PID
@@ -129,12 +76,6 @@ function matchesObservedRegistration(current, observed) {
129
76
  current.lifecycleMode === observed.lifecycleMode &&
130
77
  current.createdAt === observed.createdAt);
131
78
  }
132
- function matchesIdentity(registration, identity) {
133
- return (registration?.rootId === identity.rootId &&
134
- registration.hostEpoch === identity.hostEpoch &&
135
- registration.pid === identity.pid &&
136
- registration.lifecycleMode === 'ephemeral');
137
- }
138
79
  async function waitForExit(pid, dependencies) {
139
80
  const deadline = Date.now() + dependencies.settleMs;
140
81
  while (dependencies.isProcessAlive(pid)) {
@@ -23,6 +23,7 @@ export class RuntimeHostRemoteCompatibilityError extends RuntimeHostPermanentRec
23
23
  name = 'RuntimeHostRemoteCompatibilityError';
24
24
  code = RUNTIME_HOST_REMOTE_INCOMPATIBLE_CODE;
25
25
  details;
26
+ hostEpoch;
26
27
  constructor(profileId, handshake) {
27
28
  const details = Object.freeze({
28
29
  profileId,
@@ -42,6 +43,7 @@ export class RuntimeHostRemoteCompatibilityError extends RuntimeHostPermanentRec
42
43
  });
43
44
  super(formatRuntimeHostRemoteCompatibilityMessage(details));
44
45
  this.details = details;
46
+ this.hostEpoch = handshake.hostEpoch;
45
47
  }
46
48
  }
47
49
  function formatRuntimeHostRemoteCompatibilityMessage(details) {
@@ -42,6 +42,7 @@ export class ClientSessionSubscription {
42
42
  #releaseTranscriptOverlay;
43
43
  #expectedSessionId;
44
44
  #queue = [];
45
+ #ptyListeners = new Set();
45
46
  #queuedBytes = 0;
46
47
  #expectedSequence;
47
48
  #latestProjectionRevision;
@@ -72,6 +73,12 @@ export class ClientSessionSubscription {
72
73
  [Symbol.asyncIterator]() {
73
74
  return this;
74
75
  }
76
+ subscribePtyData(listener) {
77
+ if (this.#done || this.#terminalError || this.#closing)
78
+ return () => undefined;
79
+ this.#ptyListeners.add(listener);
80
+ return () => this.#ptyListeners.delete(listener);
81
+ }
75
82
  next() {
76
83
  const queued = this.#queue.shift();
77
84
  if (queued) {
@@ -101,6 +108,7 @@ export class ClientSessionSubscription {
101
108
  if (this.#done || this.#terminalError)
102
109
  return Promise.resolve();
103
110
  this.#closing = true;
111
+ this.#ptyListeners.clear();
104
112
  if (!this.#closeTask)
105
113
  this.#closeTask = this.#requestClose();
106
114
  return this.#closeTask;
@@ -208,9 +216,6 @@ export class ClientSessionSubscription {
208
216
  }
209
217
  const overlay = await this.#consumeTranscriptOverlay(bootstrap);
210
218
  const durable = await this.#loadTranscriptSource(bootstrap.durable);
211
- if (bootstrap.durableCoverage === 'complete') {
212
- assertCompleteIdentities(durable, bootstrap.throughSequence);
213
- }
214
219
  const messages = durable.map((entry) => entry.value);
215
220
  const indexById = new Map();
216
221
  for (const [index, message] of messages.entries()) {
@@ -317,6 +322,22 @@ export class ClientSessionSubscription {
317
322
  if (frame.subscriptionId !== this.subscriptionId) {
318
323
  throw new RuntimeHostSubscriptionError('correlation_changed', 'Session subscription correlation changed');
319
324
  }
325
+ if (frame.kind === 'subscription.runtime_resource_pty_data') {
326
+ if (frame.sessionId !== this.#expectedSessionId) {
327
+ throw new RuntimeHostSubscriptionError('correlation_changed', 'PTY Session identity changed');
328
+ }
329
+ // No iterator backlog when nobody is displaying a terminal. Attaching
330
+ // consumers hydrate from a snapshot, including bytes before attachment.
331
+ for (const listener of this.#ptyListeners) {
332
+ try {
333
+ listener(frame);
334
+ }
335
+ catch {
336
+ /* A display consumer cannot terminate Session state. */
337
+ }
338
+ }
339
+ return;
340
+ }
320
341
  if (frame.sequence !== this.#expectedSequence) {
321
342
  throw new RuntimeHostSubscriptionError('sequence_gap', `Session subscription expected sequence ${this.#expectedSequence} but received ${frame.sequence}`);
322
343
  }
@@ -333,8 +354,7 @@ export class ClientSessionSubscription {
333
354
  else if ((frame.kind === 'subscription.session_delta' ||
334
355
  frame.kind === 'subscription.session_event' ||
335
356
  frame.kind === 'subscription.transcript_advanced' ||
336
- frame.kind === 'subscription.session_domain_changed' ||
337
- frame.kind === 'subscription.runtime_resource_pty_data') &&
357
+ frame.kind === 'subscription.session_domain_changed') &&
338
358
  frame.sessionId !== this.#expectedSessionId) {
339
359
  throw new RuntimeHostSubscriptionError('correlation_changed', 'Session subscription frame identity changed');
340
360
  }
@@ -354,6 +374,7 @@ export class ClientSessionSubscription {
354
374
  this.#doneAfterQueue = true;
355
375
  }
356
376
  finish() {
377
+ this.#ptyListeners.clear();
357
378
  if (this.#done || this.#terminalError)
358
379
  return;
359
380
  this.#doneAfterQueue = true;
@@ -364,6 +385,7 @@ export class ClientSessionSubscription {
364
385
  }
365
386
  }
366
387
  fail(error) {
388
+ this.#ptyListeners.clear();
367
389
  if (this.#done || this.#terminalError)
368
390
  return;
369
391
  this.#terminalError = error;
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ export { RUNTIME_HOST_OPERATOR_RETIREMENT_CANCELLATION_ENV } from './retirement-cancellation.js';
19
20
  export { RUNTIME_HOST_ACTIVATION_ERROR_CODE_MAX_BYTES, RUNTIME_HOST_ACTIVATION_ERROR_MESSAGE_MAX_BYTES, RUNTIME_HOST_ACTIVATION_FRAME_MAX_BYTES, RUNTIME_HOST_ACTIVATION_FRAME_PREFIX, decodeRuntimeHostActivationFrame, encodeRuntimeHostActivationFrame, } from './activation-frame.js';
20
21
  export { RUNTIME_HOST_ACCESS_MANAGEMENT_ERROR_CODE_MAX_BYTES, RUNTIME_HOST_ACCESS_MANAGEMENT_ERROR_MESSAGE_MAX_BYTES, RUNTIME_HOST_ACCESS_MANAGEMENT_FRAME_PREFIX, decodeRuntimeHostAccessManagementFrame, encodeRuntimeHostAccessManagementFrame, } from './access-management-frame.js';
21
22
  export { runtimeHostAccessCredentialFingerprint } from '../access-credential-identity.js';
@@ -27,6 +28,6 @@ export { RUNTIME_HOST_OPERATOR_ACCESS_MANAGEMENT_CAPABILITY, RUNTIME_HOST_OPERAT
27
28
  export { RUNTIME_HOST_SETUP_ERROR_CODE_MAX_BYTES, RUNTIME_HOST_SETUP_ERROR_MESSAGE_MAX_BYTES, RUNTIME_HOST_SETUP_FRAME_PREFIX, decodeRuntimeHostSetupFrame, encodeRuntimeHostSetupFrame, parseRuntimeHostSetupEndpoint, } from './setup-frame.js';
28
29
  export { createRuntimeHostOperatorCommand, createRuntimeHostLegacyPosixOperatorCommand, decodeRuntimeHostOperatorCommand, decodeRuntimeHostPosixOperatorCommand, runtimeHostManagedOperatorCommand, runtimeHostManagedOperatorModulePath, runtimeHostOperatorInvocation, } from './operator-command.js';
29
30
  export { RUNTIME_HOST_SETUP_SOURCE_PACKAGE_INTEGRITY_ENV, compareProductReleaseVersions, isProductReleaseVersion, isRuntimeHostNpmDeploymentIdentity, isSha512PackageIntegrity, resolveRuntimeHostNpmDeploymentLayout, } from './update-package-evidence.js';
30
- export { applyLocalHostDeploymentTransition, LocalHostDeploymentAuthorityError, readLocalHostDeploymentRecord, resolveLocalHostDeploymentAuthorityRoot, } from './local-deployment-owner.js';
31
+ export { applyLocalHostDeploymentTransition, LocalHostDeploymentAuthorityError, readLocalHostDeploymentRecord, withLocalHostDeploymentAuthority, resolveLocalHostDeploymentAuthorityRoot, } from './local-deployment-owner.js';
31
32
  export { claimLocalHostProcessDeployment, handoffLocalHostProcessDeployment, } from './local-process-deployment-handoff.js';
32
33
  export { RUNTIME_HOST_MANAGED_DEPLOYMENT_CONFIG_FILE, RuntimeHostManagedDeploymentError, beginRuntimeHostManagedDeploymentTransition, blockRuntimeHostManagedDeploymentTransition, claimRuntimeHostManagedDeployment, commitRuntimeHostManagedDeploymentTransition, commitRuntimeHostManagedDeployment, decodeRuntimeHostManagedDeploymentAuthorityRecord, decodeRuntimeHostManagedDeploymentConfig, readRuntimeHostManagedDeploymentAuthorityRecord, assertRuntimeHostManagedDeploymentAuthorityDurablyAbsent, readRuntimeHostManagedDeploymentConfig, resolveRuntimeHostManagedDeployment, resolveRuntimeHostManagedDeploymentAuthority, resolveRuntimeHostManagedDeploymentAuthorityRoot, resolveRuntimeHostManagedDeploymentConfigPath, rollbackRuntimeHostManagedDeploymentTransition, runtimeHostManagedLaunchClaim, } from './managed-deployment.js';
@@ -0,0 +1,20 @@
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
+ /** EOF on inherited stdin cancels only the first retirement, never its transaction or rollback. */
20
+ export const RUNTIME_HOST_OPERATOR_RETIREMENT_CANCELLATION_ENV = 'MAKA_RUNTIME_HOST_OPERATOR_RETIREMENT_CANCELLATION_STDIN';