maka-agent 0.2.0-dev.40.20260917 → 0.2.0-dev.42.20260918

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 (44) hide show
  1. package/LICENSE +7 -4
  2. package/dist/runtime-host-session-driver.js +3 -8
  3. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  4. package/node_modules/@maka/core/dist/client-plugin-bridge.js +19 -0
  5. package/node_modules/@maka/core/dist/events.js +58 -7
  6. package/node_modules/@maka/core/dist/interaction.js +38 -4
  7. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  8. package/node_modules/@maka/core/dist/model-metadata.js +89 -0
  9. package/node_modules/@maka/core/dist/recall.js +198 -15
  10. package/node_modules/@maka/core/dist/redaction.js +8 -0
  11. package/node_modules/@maka/core/dist/session-reference.js +149 -0
  12. package/node_modules/@maka/core/dist/shell-run.js +11 -0
  13. package/node_modules/@maka/core/package.json +2 -0
  14. package/node_modules/@maka/runtime/dist/model-factory.js +5 -3
  15. package/node_modules/@maka/runtime/dist/model-history.js +13 -2
  16. package/node_modules/@maka/runtime/dist/plugin-client-bridge-service.js +308 -0
  17. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +4 -3
  18. package/node_modules/@maka/runtime/dist/plugin-data-services.js +3 -3
  19. package/node_modules/@maka/runtime/dist/pty-screen-collector.js +32 -6
  20. package/node_modules/@maka/runtime/dist/recall-tools.js +70 -2
  21. package/node_modules/@maka/runtime/dist/shell-run-manager.js +52 -21
  22. package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +4 -2
  23. package/node_modules/@maka/runtime/package.json +1 -0
  24. package/node_modules/@maka/runtime-host/dist/protocol/index.js +9 -1
  25. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +5 -0
  26. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +269 -0
  27. package/node_modules/@maka/runtime-host/dist/protocol/runtime-resource.js +4 -17
  28. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +2 -0
  29. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +46 -6
  30. package/node_modules/@maka/runtime-host/dist/server/extension-package-manifest.js +19 -1
  31. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +9 -1
  32. package/node_modules/@maka/runtime-host/dist/server/plugin-package-loader.js +88 -14
  33. package/node_modules/@maka/runtime-host/dist/server/plugin-package-store.js +22 -5
  34. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +122 -1
  35. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +120 -1
  36. package/node_modules/@maka/runtime-host/dist/server/recall-material-fetch.js +92 -0
  37. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +14 -1
  38. package/node_modules/@maka/runtime-host/dist/server/runtime-resource-coordinator.js +13 -23
  39. package/node_modules/@maka/runtime-host/dist/server/runtime-resource-projection.js +5 -16
  40. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +17 -1
  41. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +67 -3
  42. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +9 -3
  43. package/node_modules/@maka/runtime-host/dist/server/workhub-target-execution-authority.js +161 -0
  44. package/package.json +1 -1
@@ -0,0 +1,308 @@
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 { Service, } from './plugin-kernel.js';
20
+ import { PluginScopeRegistry } from './plugin-scope-registry.js';
21
+ import { MakaPluginRuntimeError, pluginIdentity, registerPluginContribution, } from './plugin-runtime.js';
22
+ export class PluginClientBridgeError extends Error {
23
+ code;
24
+ name = 'PluginClientBridgeError';
25
+ constructor(code, message) {
26
+ super(message);
27
+ this.code = code;
28
+ }
29
+ }
30
+ /** Fiber-owned Host half of one package's typed Client Remote contract. */
31
+ export class PluginClientBridgeService extends Service {
32
+ rpcs = new PluginScopeRegistry();
33
+ streams = new PluginScopeRegistry();
34
+ constructor(ctx) {
35
+ super(ctx, 'clientBridge');
36
+ }
37
+ rpc(definition) {
38
+ validateDefinition(definition, 'RPC');
39
+ const identity = hostIdentity(this.ctx);
40
+ return registerPluginContribution(this.ctx, `clientBridge.rpc(${JSON.stringify(definition.name)})`, () => this.publish(this.rpcs, identity, definition));
41
+ }
42
+ stream(definition) {
43
+ validateDefinition(definition, 'Stream');
44
+ const identity = hostIdentity(this.ctx);
45
+ return registerPluginContribution(this.ctx, `clientBridge.stream(${JSON.stringify(definition.name)})`, () => this.publish(this.streams, identity, definition));
46
+ }
47
+ async invoke(target, name, input, signal) {
48
+ return await this.prepareInvoke(target, name, input, signal)();
49
+ }
50
+ /** Capture the verified registration before releasing the platform mutation lock. */
51
+ prepareInvoke(target, name, input, signal) {
52
+ const entry = resolve(this.rpcs, target, name);
53
+ return async () => await this.invokeEntry(entry, target, name, input, signal);
54
+ }
55
+ async invokeEntry(entry, target, name, input, signal) {
56
+ const active = activate(entry, name, signal);
57
+ try {
58
+ const decoded = await untilAborted(active.abort.signal, () => validateInputSchema(entry.definition.input, input, `Client RPC ${name} input`));
59
+ const output = await untilAborted(active.abort.signal, () => entry.definition.invoke(decoded, {
60
+ ...(target.sessionId ? { sessionId: target.sessionId } : {}),
61
+ signal: active.abort.signal,
62
+ }));
63
+ if (entry.retired)
64
+ throw retiredError(name);
65
+ return await untilAborted(active.abort.signal, () => validateSchema(entry.definition.output, output, `Client RPC ${name} output`));
66
+ }
67
+ finally {
68
+ finish(entry, active);
69
+ }
70
+ }
71
+ async open(target, name, input, signal) {
72
+ return await this.prepareOpen(target, name, input, signal)();
73
+ }
74
+ /** Capture the verified registration before releasing the platform mutation lock. */
75
+ prepareOpen(target, name, input, signal) {
76
+ const entry = resolve(this.streams, target, name);
77
+ return async () => await this.openEntry(entry, target, name, input, signal);
78
+ }
79
+ async openEntry(entry, target, name, input, signal) {
80
+ const active = activate(entry, name, signal);
81
+ try {
82
+ const decoded = await untilAborted(active.abort.signal, () => validateInputSchema(entry.definition.input, input, `Client Stream ${name} input`));
83
+ const iterable = await untilAborted(active.abort.signal, () => entry.definition.open(decoded, {
84
+ ...(target.sessionId ? { sessionId: target.sessionId } : {}),
85
+ signal: active.abort.signal,
86
+ }), (late) => {
87
+ void Promise.resolve()
88
+ .then(() => late[Symbol.asyncIterator]().return?.())
89
+ .catch(() => undefined);
90
+ });
91
+ if (!iterable || typeof iterable[Symbol.asyncIterator] !== 'function') {
92
+ throw new TypeError(`Client Stream ${name} did not return an AsyncIterable`);
93
+ }
94
+ const iterator = iterable[Symbol.asyncIterator]();
95
+ let closed = false;
96
+ const pending = new Set();
97
+ const close = async () => {
98
+ if (closed)
99
+ return;
100
+ closed = true;
101
+ active.abort.signal.removeEventListener('abort', onAbort);
102
+ active.abort.abort();
103
+ for (const settle of pending)
104
+ settle();
105
+ pending.clear();
106
+ // A generator's return queues behind its pending next. Do not let a
107
+ // non-cooperative producer block connection cleanup or Fiber retirement.
108
+ void Promise.resolve()
109
+ .then(() => iterator.return?.())
110
+ .catch(() => undefined);
111
+ finish(entry, active);
112
+ };
113
+ const onAbort = () => {
114
+ void close();
115
+ };
116
+ active.abort.signal.addEventListener('abort', onAbort, { once: true });
117
+ if (active.abort.signal.aborted)
118
+ await close();
119
+ return Object.freeze({
120
+ identity: freezeIdentity(entry),
121
+ next: async () => {
122
+ if (closed || entry.retired)
123
+ throw retiredError(name);
124
+ let settle;
125
+ const stopped = new Promise((resolve) => {
126
+ settle = () => resolve({ done: true, value: undefined });
127
+ });
128
+ pending.add(settle);
129
+ try {
130
+ const result = await Promise.race([iterator.next(), stopped]);
131
+ if (closed || result.done) {
132
+ await close();
133
+ return Object.freeze({ done: true, value: undefined });
134
+ }
135
+ const value = await Promise.race([
136
+ validateSchema(entry.definition.item, result.value, `Client Stream ${name} item`),
137
+ stopped.then(() => undefined),
138
+ ]);
139
+ if (closed)
140
+ return Object.freeze({ done: true, value: undefined });
141
+ return Object.freeze({ done: false, value });
142
+ }
143
+ finally {
144
+ pending.delete(settle);
145
+ }
146
+ },
147
+ close,
148
+ });
149
+ }
150
+ catch (error) {
151
+ finish(entry, active);
152
+ throw error;
153
+ }
154
+ }
155
+ publish(registry, identity, definition) {
156
+ const rootId = identity.scopeId;
157
+ const key = registrationKey(identity.extensionId, definition.name);
158
+ const existing = registry.get(rootId, key);
159
+ if (existing && existing.entryId !== identity.entryId) {
160
+ throw new MakaPluginRuntimeError('activation_failed', `Client Remote ${JSON.stringify(definition.name)} is already registered by ${existing.entryId}`);
161
+ }
162
+ const entry = {
163
+ ...identity,
164
+ definition: Object.freeze({ ...definition }),
165
+ token: Symbol(definition.name),
166
+ active: new Set(),
167
+ retired: false,
168
+ };
169
+ return registry.publish(rootId, key, entry, {
170
+ onRetired: async (retired) => {
171
+ for (const invocation of retired.active) {
172
+ invocation.abort.abort(retiredError(definition.name));
173
+ }
174
+ await Promise.allSettled([...retired.active].map(({ settled }) => settled));
175
+ },
176
+ });
177
+ }
178
+ }
179
+ function hostIdentity(ctx) {
180
+ const identity = pluginIdentity(ctx);
181
+ if (identity.scopeId === 'desktop-ui') {
182
+ throw new MakaPluginRuntimeError('activation_failed', 'Client Remote handlers must be registered by a Host composition entry');
183
+ }
184
+ return identity;
185
+ }
186
+ function resolve(registry, target, name) {
187
+ validateMethodName(name);
188
+ const key = registrationKey(target.extensionId, name);
189
+ const entry = target.sessionId
190
+ ? registry.visible(assertSessionId(target.sessionId)).get(key)
191
+ : registry.get('profile', key);
192
+ if (!entry || entry.retired) {
193
+ throw new PluginClientBridgeError('not_found', `Client Remote is unavailable: ${name}`);
194
+ }
195
+ return entry;
196
+ }
197
+ function activate(entry, name, signal) {
198
+ if (entry.retired)
199
+ throw retiredError(name);
200
+ const abort = new AbortController();
201
+ const onAbort = () => abort.abort(signal?.reason);
202
+ if (signal?.aborted)
203
+ onAbort();
204
+ else
205
+ signal?.addEventListener('abort', onAbort, { once: true });
206
+ let settle;
207
+ const settled = new Promise((resolve) => {
208
+ settle = resolve;
209
+ });
210
+ const active = {
211
+ abort,
212
+ settled,
213
+ settle,
214
+ onAbort,
215
+ ...(signal ? { signal } : {}),
216
+ };
217
+ entry.active.add(active);
218
+ return active;
219
+ }
220
+ function untilAborted(signal, run, late) {
221
+ return new Promise((resolve, reject) => {
222
+ if (signal.aborted) {
223
+ reject(signal.reason);
224
+ return;
225
+ }
226
+ let settled = false;
227
+ const abort = () => {
228
+ settled = true;
229
+ reject(signal.reason);
230
+ };
231
+ signal.addEventListener('abort', abort, { once: true });
232
+ void Promise.resolve()
233
+ .then(() => {
234
+ signal.throwIfAborted();
235
+ return run();
236
+ })
237
+ .then((value) => {
238
+ signal.removeEventListener('abort', abort);
239
+ if (settled) {
240
+ late?.(value);
241
+ return;
242
+ }
243
+ settled = true;
244
+ resolve(value);
245
+ }, (error) => {
246
+ signal.removeEventListener('abort', abort);
247
+ if (!settled) {
248
+ settled = true;
249
+ reject(error);
250
+ }
251
+ })
252
+ .catch(() => undefined);
253
+ });
254
+ }
255
+ function finish(entry, active) {
256
+ entry.active.delete(active);
257
+ active.signal?.removeEventListener('abort', active.onAbort);
258
+ active.settle();
259
+ }
260
+ function freezeIdentity(entry) {
261
+ return Object.freeze({
262
+ entryId: entry.entryId,
263
+ scopeId: entry.scopeId,
264
+ extensionId: entry.extensionId,
265
+ generation: entry.generation,
266
+ });
267
+ }
268
+ async function validateSchema(schema, value, label) {
269
+ if (!schema)
270
+ return value;
271
+ const result = await schema['~standard'].validate(value);
272
+ if (result.issues) {
273
+ throw new TypeError(`${label} is invalid: ${result.issues.map(({ message }) => message).join('; ')}`);
274
+ }
275
+ return result.value;
276
+ }
277
+ async function validateInputSchema(schema, value, label) {
278
+ try {
279
+ return await validateSchema(schema, value, label);
280
+ }
281
+ catch (error) {
282
+ throw new PluginClientBridgeError('invalid_input', error instanceof Error ? error.message : `${label} is invalid`);
283
+ }
284
+ }
285
+ function retiredError(name) {
286
+ return new PluginClientBridgeError('retired', `Client Remote retired while active: ${name}`);
287
+ }
288
+ function validateDefinition(definition, label) {
289
+ validateMethodName(definition.name);
290
+ if (('invoke' in definition && typeof definition.invoke !== 'function') ||
291
+ ('open' in definition && typeof definition.open !== 'function')) {
292
+ throw new TypeError(`Client ${label} handler is required`);
293
+ }
294
+ }
295
+ function validateMethodName(name) {
296
+ if (!/^[a-z][a-z0-9]*(?:[._:/-][a-z0-9]+)*$/u.test(name) || name.length > 128) {
297
+ throw new TypeError('Client Remote name is invalid');
298
+ }
299
+ }
300
+ function registrationKey(extensionId, name) {
301
+ return `${extensionId}\u0000${name}`;
302
+ }
303
+ function assertSessionId(value) {
304
+ if (!value || value.length > 128 || /[\0\r\n]/u.test(value)) {
305
+ throw new TypeError('Client Remote Session id is invalid');
306
+ }
307
+ return value;
308
+ }
@@ -459,8 +459,9 @@ export class MakaCompositionLoader {
459
459
  const pkg = this.#packages.get(spec.packageId);
460
460
  if (!pkg)
461
461
  throw new MakaPluginRuntimeError('package_not_found', `Plugin package is not installed: ${spec.packageId}`);
462
- if (!pkg.host)
463
- throw new MakaPluginRuntimeError('invalid_package', `Plugin package has no Host plugin: ${spec.packageId}`);
462
+ const selectedPlugin = rootId === 'desktop-ui' ? pkg.client : pkg.host;
463
+ if (!selectedPlugin)
464
+ throw new MakaPluginRuntimeError('invalid_package', `Plugin package has no ${rootId === 'desktop-ui' ? 'Client' : 'Host'} plugin: ${spec.packageId}`);
464
465
  const generation = ++this.#fiberGeneration;
465
466
  const metadata = Object.freeze({
466
467
  rootId,
@@ -474,7 +475,7 @@ export class MakaCompositionLoader {
474
475
  context = context.extend({ makaTransaction: transaction });
475
476
  live.context = context;
476
477
  live.generation = generation;
477
- const plugin = entryPlugin(pkg.host, spec.inject);
478
+ const plugin = entryPlugin(selectedPlugin, spec.inject);
478
479
  live.fiber = context.plugin(plugin, spec.config);
479
480
  try {
480
481
  await live.fiber.await();
@@ -59,10 +59,10 @@ class PluginNamespacedDataService extends Service {
59
59
  }))));
60
60
  }
61
61
  watchValues(listener) {
62
- const subscribe = this.runtime().subscribe;
63
- if (!subscribe)
62
+ const runtime = this.runtime();
63
+ if (!runtime.subscribe)
64
64
  throw new Error(`Plugin ${this.domain} subscriptions are unavailable`);
65
- return subscribe(this.namespace(), this.domain, listener);
65
+ return runtime.subscribe(this.namespace(), this.domain, listener);
66
66
  }
67
67
  }
68
68
  /** Per-extension Settings with schema contributions, CAS revisions, and no global-policy access. */
@@ -66,6 +66,9 @@ export class PtyScreenCollector {
66
66
  this.installProtocolBoundary();
67
67
  this.lastGood = blankPtyOutput(cols, rows);
68
68
  }
69
+ get available() {
70
+ return !this.failure && !this.disposed;
71
+ }
69
72
  accept(data) {
70
73
  if (!data)
71
74
  return;
@@ -75,23 +78,46 @@ export class PtyScreenCollector {
75
78
  }
76
79
  const generation = ++this.admittedGeneration;
77
80
  const bytes = Buffer.byteLength(data, 'utf8');
78
- const entry = { data, bytes, dropped: false };
81
+ // node-pty delivers many tiny events per tick; each queued parse is paced
82
+ // by the headless terminal's write scheduler, so queue depth — not byte
83
+ // volume — is what stalls cut-bound operations. Merge unstarted data into
84
+ // the tail entry: byte order is preserved and protocol replies already
85
+ // batch per write call.
86
+ const tail = this.pending.at(-1);
87
+ if (tail &&
88
+ !tail.dropped &&
89
+ !tail.started &&
90
+ tail.bytes + bytes <= PTY_PARSER_HIGH_WATER_BYTES) {
91
+ tail.data += data;
92
+ tail.bytes += bytes;
93
+ tail.generation = generation;
94
+ }
95
+ else {
96
+ this.enqueue({ data, bytes, generation, dropped: false, started: false });
97
+ }
79
98
  this.pendingBytes += bytes;
80
- this.pending.push(entry);
81
99
  this.evictOldestIfOverBudget();
82
100
  this.options.onDirty(generation);
83
- const parse = this.sequence.then(() => (entry.dropped ? undefined : this.write(entry.data)));
101
+ }
102
+ enqueue(entry) {
103
+ this.pending.push(entry);
104
+ const parse = this.sequence.then(() => {
105
+ if (entry.dropped)
106
+ return undefined;
107
+ entry.started = true;
108
+ return this.write(entry.data);
109
+ });
84
110
  this.sequence = parse.then(() => {
85
111
  if (entry.dropped)
86
112
  return;
87
- this.parsedGeneration = generation;
88
- this.pendingBytes -= bytes;
113
+ this.parsedGeneration = entry.generation;
114
+ this.pendingBytes -= entry.bytes;
89
115
  const index = this.pending.indexOf(entry);
90
116
  if (index >= 0)
91
117
  this.pending.splice(index, 1);
92
118
  }, (error) => {
93
119
  if (!entry.dropped)
94
- this.pendingBytes -= bytes;
120
+ this.pendingBytes -= entry.bytes;
95
121
  this.fail(asError(error, 'PTY parser failed'));
96
122
  });
97
123
  }
@@ -16,18 +16,22 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { expandRecallPassage, RECALL_EXPAND_MAX_NEIGHBOURS, RECALL_ID_MAX_CHARS, RECALL_DEFAULT_LIMIT, RECALL_MAX_LIMIT, RECALL_MAX_TERMS, runRecall, } from '@maka/core/recall';
19
+ import { expandRecallPassage, fetchRecallMaterial, RECALL_EXPAND_MAX_NEIGHBOURS, RECALL_ID_MAX_CHARS, RECALL_DEFAULT_LIMIT, RECALL_MAX_LIMIT, RECALL_MAX_TERMS, runRecall, } from '@maka/core/recall';
20
20
  import { SEARCH_QUERY_MAX_CHARS } from '@maka/core/search';
21
21
  import { z } from 'zod';
22
22
  export const RECALL_TOOL_NAME = 'Recall';
23
23
  export const RECALL_MORE_TOOL_NAME = 'RecallMore';
24
+ export const RECALL_MATERIAL_TOOL_NAME = 'RecallMaterial';
24
25
  /**
25
26
  * Builds the read-only recall surface: one call that answers "what do I
26
27
  * already know about this", and an expansion for the passage that needs more
27
28
  * of its exchange than the envelope carried.
28
29
  */
29
30
  export function buildRecallTools(deps) {
30
- return [buildRecallTool(deps), buildRecallMoreTool(deps)];
31
+ const tools = [buildRecallTool(deps), buildRecallMoreTool(deps)];
32
+ // A host with no artifact store cannot fetch anything, and a tool that can
33
+ // only refuse is worse than one the model never sees.
34
+ return deps.fetchMaterial ? [...tools, buildRecallMaterialTool(deps)] : tools;
31
35
  }
32
36
  export function buildRecallTool(deps) {
33
37
  return {
@@ -39,6 +43,10 @@ export function buildRecallTool(deps) {
39
43
  'Supply a few distinct literal terms rather than a sentence: matching is case-insensitive substring, OR-combined, ' +
40
44
  'and results rank higher when they contain more of the terms. Returns distilled facts, ranked transcript passages ' +
41
45
  'that already carry the surrounding exchange, and a note on what the search did not reach. ' +
46
+ 'A message that carried files lists them under materials, matched by file name. A material carrying a resource ' +
47
+ 'address can be opened with Read, which answers an image with the image and any other file with its text; a ' +
48
+ 'material without one carries source_session_id and material_id instead: pass those to RecallMaterial to ' +
49
+ 'bring the file here. A material with neither cannot be retrieved at all. ' +
42
50
  'One Recall call usually suffices; use RecallMore only when a passage is cut short.',
43
51
  parameters: z
44
52
  .object({
@@ -117,6 +125,45 @@ export function buildRecallTool(deps) {
117
125
  },
118
126
  };
119
127
  }
128
+ export function buildRecallMaterialTool(deps) {
129
+ return {
130
+ name: RECALL_MATERIAL_TOOL_NAME,
131
+ displayName: 'Open a recalled file',
132
+ activityKind: 'read',
133
+ categoryHint: 'read',
134
+ description: 'Open a file a Recall passage named but could not hand you directly, using its source_session_id ' +
135
+ 'and material_id. The file is copied into this Session and returned the way Read returns one ' +
136
+ 'stored here, so it stays readable afterwards; opening the same material again reuses that copy. ' +
137
+ 'Only files a person attached are retrievable, and only from Sessions Recall can already see. ' +
138
+ 'A material that came back with a resource address needs no retrieval — read that address instead.',
139
+ parameters: z
140
+ .object({
141
+ session_id: z
142
+ .string()
143
+ .trim()
144
+ .min(1)
145
+ .max(RECALL_ID_MAX_CHARS)
146
+ .describe('The material source_session_id from a Recall passage.'),
147
+ material_id: z
148
+ .string()
149
+ .trim()
150
+ .min(1)
151
+ .max(RECALL_ID_MAX_CHARS)
152
+ .describe('The material_id from a Recall passage.'),
153
+ })
154
+ .strict(),
155
+ impl: async ({ session_id: sessionId, material_id: materialId }, context) => {
156
+ const result = await fetchRecallMaterial({ sessionId, materialId }, deps, {
157
+ activeSessionId: context.sessionId,
158
+ includeArchived: true,
159
+ abortSignal: context.abortSignal,
160
+ });
161
+ if (!result.ok)
162
+ return recallError(result);
163
+ return result.content;
164
+ },
165
+ };
166
+ }
120
167
  export function buildRecallMoreTool(deps) {
121
168
  return {
122
169
  name: RECALL_MORE_TOOL_NAME,
@@ -197,6 +244,27 @@ function projectPassage(passage, activeSessionId) {
197
244
  timestamp: message.timestamp,
198
245
  ...(message.isAnchor ? { is_anchor: true } : {}),
199
246
  text: message.text,
247
+ // Metadata only. `resource` is present exactly when the file is
248
+ // readable from the Session asking; elsewhere the material is named
249
+ // but has no address, because an attachment read resolves against the
250
+ // calling Session and would refuse one stored in another.
251
+ ...(message.materials
252
+ ? {
253
+ materials: message.materials.map((material) => ({
254
+ name: material.name,
255
+ kind: material.kind,
256
+ mime_type: material.mimeType,
257
+ bytes: material.bytes,
258
+ ...(material.resource ? { resource: material.resource } : {}),
259
+ ...(material.sourceSessionId && material.materialId
260
+ ? {
261
+ source_session_id: material.sourceSessionId,
262
+ material_id: material.materialId,
263
+ }
264
+ : {}),
265
+ })),
266
+ }
267
+ : {}),
200
268
  })),
201
269
  };
202
270
  }
@@ -241,7 +241,7 @@ export class ShellRunProcessManager {
241
241
  let resizeChanged = false;
242
242
  let operationFailed = false;
243
243
  let exitBeforeControlCut = false;
244
- const controlCut = live.collector.mutateAndSnapshotAtCut(() => {
244
+ const mutation = () => {
245
245
  if (input.abortSignal?.aborted) {
246
246
  throw abortError('WriteStdin aborted before the control operation was committed');
247
247
  }
@@ -287,8 +287,18 @@ export class ShellRunProcessManager {
287
287
  this.handleIntegrityFailure(live, asError(error, 'PTY input write failed'));
288
288
  }
289
289
  }
290
- });
291
- const persistedControl = this.persistObservation(live, controlCut.then((snapshot) => (operationFailed || exitBeforeControlCut ? undefined : snapshot), () => undefined));
290
+ };
291
+ // Client control replies carry no output, so the keystroke path only needs
292
+ // the ordered mutation, not the snapshot + persist. The record still
293
+ // refreshes through output-driven flushes; a resize changes the screen
294
+ // without output, so that one is persisted eagerly.
295
+ const clientControl = input.caller === 'client';
296
+ const controlCut = clientControl
297
+ ? live.collector.mutateAtCut(mutation).then(() => undefined)
298
+ : live.collector.mutateAndSnapshotAtCut(mutation);
299
+ const persistedControl = clientControl
300
+ ? undefined
301
+ : this.persistObservation(live, controlCut.then((snapshot) => (operationFailed || exitBeforeControlCut ? undefined : snapshot), () => undefined));
292
302
  try {
293
303
  await controlCut;
294
304
  }
@@ -312,20 +322,27 @@ export class ShellRunProcessManager {
312
322
  return shellRunContent(record, operation);
313
323
  }
314
324
  let record;
315
- try {
316
- record = await persistedControl;
317
- }
318
- catch (error) {
319
- if (live.integrityFailure && !live.persistFailure) {
320
- record = await this.markObserved(await live.finished.join());
321
- return shellRunContent(record, ptyControlOperation(input, {
322
- inputQueued,
323
- resizeApplied,
324
- resizeChanged,
325
- failed: true,
326
- }));
325
+ if (persistedControl) {
326
+ try {
327
+ record = await persistedControl;
327
328
  }
328
- throw error;
329
+ catch (error) {
330
+ if (live.integrityFailure && !live.persistFailure) {
331
+ record = await this.markObserved(await live.finished.join());
332
+ return shellRunContent(record, ptyControlOperation(input, {
333
+ inputQueued,
334
+ resizeApplied,
335
+ resizeChanged,
336
+ failed: true,
337
+ }));
338
+ }
339
+ throw error;
340
+ }
341
+ }
342
+ else {
343
+ record = live.record;
344
+ if (resizeChanged)
345
+ void this.persistObservation(live).catch(() => undefined);
329
346
  }
330
347
  if (live.integrityFailure && !live.persistFailure) {
331
348
  record = await this.markObserved(await live.finished.join());
@@ -336,7 +353,6 @@ export class ShellRunProcessManager {
336
353
  failed: true,
337
354
  }));
338
355
  }
339
- // persistObservation decides whether to join finalization at call time.
340
356
  // A real PTY can exit while that persist is still in flight, leaving a
341
357
  // running snapshot here even though finalizeOnce has already started.
342
358
  if (live.driverExit || live.finalizeOnce) {
@@ -345,7 +361,7 @@ export class ShellRunProcessManager {
345
361
  }
346
362
  if (isTerminalShellRunStatus(record.status))
347
363
  record = await this.markObserved(record);
348
- return shellRunContent(record, operation);
364
+ return clientControl ? compactShellRunContent(record) : shellRunContent(record, operation);
349
365
  }
350
366
  async readRuntimeResource(sessionId, ref, abortSignal) {
351
367
  return this.resourceDetail(sessionId, ref, true, abortSignal, true);
@@ -428,11 +444,21 @@ export class ShellRunProcessManager {
428
444
  const live = this.live.get(target.shellRunId);
429
445
  if (!live || live.sessionId !== sessionId || live.mode !== 'pty')
430
446
  return null;
447
+ // The collector dies before the process exit lands: an integrity failure or
448
+ // startup cleanup leaves it throwing while `live` still looks attachable.
449
+ // Report the resource as gone so the caller repairs the stale record.
450
+ if (live.driverExit || live.finalizeOnce || live.integrityFailure)
451
+ return null;
452
+ if (!live.collector.available)
453
+ return null;
454
+ // Flush pending bytes first so the snapshot sequence always names the last
455
+ // published event the buffer already contains.
456
+ this.publishPtyData(live);
431
457
  return {
432
458
  sessionId,
433
459
  ref,
434
460
  sequence: live.rawSequence,
435
- buffer: live.rawBuffer,
461
+ buffer: live.rawBuffer.slice(-PTY_RAW_REPLAY_CHARS),
436
462
  size: live.collector.currentSize(),
437
463
  };
438
464
  }
@@ -762,14 +788,18 @@ export class ShellRunProcessManager {
762
788
  onPtyData(live, data) {
763
789
  if (live.driverExit || live.finalizeOnce)
764
790
  return;
765
- live.rawBuffer = `${live.rawBuffer}${data}`.slice(-PTY_RAW_REPLAY_CHARS);
791
+ // Amortize the tail trim: slicing on every tiny node-pty event copies the
792
+ // whole 16K replay buffer per event.
793
+ live.rawBuffer += data;
794
+ if (live.rawBuffer.length > PTY_RAW_REPLAY_CHARS * 2) {
795
+ live.rawBuffer = live.rawBuffer.slice(-PTY_RAW_REPLAY_CHARS);
796
+ }
766
797
  live.collector.accept(data);
767
798
  for (const chunk of splitPtyData(data)) {
768
799
  const combined = `${live.pendingRawData}${chunk}`;
769
800
  if (live.pendingRawData && encodedPtyDataBytes(combined) > PTY_RAW_PUBLISH_MAX_BYTES) {
770
801
  this.publishPtyData(live);
771
802
  }
772
- live.rawSequence += 1;
773
803
  live.pendingRawData += chunk;
774
804
  if (encodedPtyDataBytes(live.pendingRawData) >= PTY_RAW_PUBLISH_TARGET_BYTES) {
775
805
  this.publishPtyData(live);
@@ -791,6 +821,7 @@ export class ShellRunProcessManager {
791
821
  if (!data)
792
822
  return;
793
823
  live.pendingRawData = '';
824
+ live.rawSequence += 1;
794
825
  const event = {
795
826
  sessionId: live.sessionId,
796
827
  ref: shellRunResourceRef(live.shellRunId),
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { encodedTerminalInputActionsByteLength } from '@maka/core/terminal-input';
20
- import { isActiveShellRunStatus } from '@maka/core/shell-run';
20
+ import { isActiveShellRunStatus, isDesktopTerminalShellRun } from '@maka/core/shell-run';
21
21
  import { shellRunResourceRef } from './shell-run-contract.js';
22
22
  import { truncateToolOutput } from './tool-output.js';
23
23
  import { isLikelySandboxDenial } from './sandbox/detect.js';
@@ -29,7 +29,9 @@ export function shellRunUpdate(record) {
29
29
  ownership: { kind: 'local' },
30
30
  sourceTurnId: record.sourceTurnId,
31
31
  sourceToolCallId: record.sourceToolCallId,
32
- result: shellRunSnapshotContent(record),
32
+ result: isDesktopTerminalShellRun({ ...record, mode: record.output.mode })
33
+ ? shellRunStateContent(record)
34
+ : shellRunSnapshotContent(record),
33
35
  };
34
36
  }
35
37
  export function terminalContent(record) {