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
@@ -16,14 +16,19 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { randomUUID } from 'node:crypto';
20
- import { cp, mkdir, rm } from 'node:fs/promises';
19
+ import { createHash, randomUUID } from 'node:crypto';
20
+ import { cp, mkdir, open, readFile, readdir, rm } from 'node:fs/promises';
21
21
  import { join, relative } from 'node:path';
22
22
  import { pathToFileURL } from 'node:url';
23
23
  import { MakaPluginRuntimeError, validatePluginPackage, } from '@maka/runtime/plugin-runtime';
24
24
  import { PluginPackageStoreError, } from './plugin-package-store.js';
25
25
  const GENERATION_DIRECTORY = 'plugin-generations-v1';
26
26
  const GENERATION_PATH = Symbol('maka.pluginGenerationPath');
27
+ const CLIENT_BUNDLE = Symbol('maka.clientPluginBundle');
28
+ const clientMarker = Object.freeze({
29
+ name: 'maka-client-composition-marker',
30
+ apply() { },
31
+ });
27
32
  export class PluginPackageLoaderError extends Error {
28
33
  code;
29
34
  name = 'PluginPackageLoaderError';
@@ -61,20 +66,42 @@ export class TrustedPluginPackageLoader {
61
66
  errorOnExist: true,
62
67
  preserveTimestamps: false,
63
68
  });
64
- const entry = join(generation, relative(installed.root, installed.entry));
65
- const imported = (await import(pathToFileURL(entry).href));
66
- const candidate = imported.default ?? imported.plugin;
67
- if (!candidate || typeof candidate !== 'object') {
68
- throw invalid('Plugin Runtime entry must export a MakaPluginPackage as default');
69
+ let pkg;
70
+ if (installed.entry) {
71
+ const entry = join(generation, relative(installed.root, installed.entry));
72
+ const imported = (await import(pathToFileURL(entry).href));
73
+ const candidate = imported.default ?? imported.plugin;
74
+ if (!candidate || typeof candidate !== 'object') {
75
+ throw invalid('Plugin Runtime entry must export a MakaPluginPackage as default');
76
+ }
77
+ pkg = candidate;
69
78
  }
70
- const pkg = candidate;
79
+ else {
80
+ pkg = { packageId: installed.extensionId, client: clientMarker };
81
+ }
82
+ if (installed.clientEntry)
83
+ pkg = { ...pkg, client: clientMarker };
71
84
  validatePluginPackage(pkg);
72
85
  if (pkg.packageId !== installed.extensionId) {
73
86
  throw invalid(`Plugin Runtime packageId ${pkg.packageId} does not match manifest ${installed.extensionId}`);
74
87
  }
75
- if (!pkg.host)
76
- throw invalid('Trusted Host package must export a host Plugin');
77
- const owned = freezeGeneration(pkg, generation);
88
+ if (installed.entry && !pkg.host) {
89
+ throw invalid('Trusted Runtime entry must export a host Plugin');
90
+ }
91
+ let clientBundle;
92
+ if (installed.clientEntry) {
93
+ const path = join(generation, relative(installed.root, installed.clientEntry));
94
+ const content = await readFile(path);
95
+ clientBundle = Object.freeze({
96
+ extensionId: installed.extensionId,
97
+ contentDigest: installed.contentDigest,
98
+ clientDigest: `sha256-${createHash('sha256').update(content).digest('hex')}`,
99
+ totalBytes: content.byteLength,
100
+ path,
101
+ generation,
102
+ });
103
+ }
104
+ const owned = freezeGeneration(pkg, generation, clientBundle);
78
105
  this.#owned.add(generation);
79
106
  return owned;
80
107
  }
@@ -84,8 +111,16 @@ export class TrustedPluginPackageLoader {
84
111
  }
85
112
  }
86
113
  async collectGarbage() {
87
- this.#owned.clear();
88
- await rm(this.#generations, { recursive: true, force: true });
114
+ const entries = await readdir(this.#generations).catch((error) => {
115
+ if (error.code === 'ENOENT')
116
+ return [];
117
+ throw error;
118
+ });
119
+ for (const name of entries) {
120
+ const path = join(this.#generations, name);
121
+ if (!this.#owned.has(path))
122
+ await rm(path, { recursive: true, force: true });
123
+ }
89
124
  }
90
125
  async release(pkg) {
91
126
  const generation = pkg[GENERATION_PATH];
@@ -93,15 +128,51 @@ export class TrustedPluginPackageLoader {
93
128
  return;
94
129
  await rm(generation, { recursive: true, force: true });
95
130
  }
131
+ clientBundle(pkg) {
132
+ const bundle = clientBundleOf(pkg);
133
+ if (!bundle || !this.#owned.has(bundle.generation))
134
+ return undefined;
135
+ return Object.freeze({
136
+ extensionId: bundle.extensionId,
137
+ contentDigest: bundle.contentDigest,
138
+ clientDigest: bundle.clientDigest,
139
+ totalBytes: bundle.totalBytes,
140
+ });
141
+ }
142
+ async readClientBundle(pkg, offset, maxBytes) {
143
+ const bundle = clientBundleOf(pkg);
144
+ if (!bundle || !this.#owned.has(bundle.generation)) {
145
+ throw new PluginPackageLoaderError('not_found', `Plugin package has no active Client generation: ${pkg.packageId}`);
146
+ }
147
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= bundle.totalBytes) {
148
+ throw invalid('Plugin Client bundle offset is invalid');
149
+ }
150
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
151
+ throw invalid('Plugin Client bundle read size is invalid');
152
+ }
153
+ const handle = await open(bundle.path, 'r');
154
+ try {
155
+ const length = Math.min(maxBytes, bundle.totalBytes - offset);
156
+ const content = Buffer.allocUnsafe(length);
157
+ const { bytesRead } = await handle.read(content, 0, length, offset);
158
+ if (bytesRead !== length)
159
+ throw invalid('Plugin Client bundle ended unexpectedly');
160
+ return Object.freeze({ content, totalBytes: bundle.totalBytes });
161
+ }
162
+ finally {
163
+ await handle.close();
164
+ }
165
+ }
96
166
  async close() {
97
167
  this.#owned.clear();
98
168
  await rm(this.#generations, { recursive: true, force: true });
99
169
  }
100
170
  }
101
- function freezeGeneration(pkg, generation) {
171
+ function freezeGeneration(pkg, generation, clientBundle) {
102
172
  return Object.freeze({
103
173
  ...pkg,
104
174
  [GENERATION_PATH]: generation,
175
+ ...(clientBundle ? { [CLIENT_BUNDLE]: clientBundle } : {}),
105
176
  ...(pkg.contributions
106
177
  ? {
107
178
  contributions: Object.freeze(pkg.contributions.map((item) => Object.freeze({ ...item }))),
@@ -109,6 +180,9 @@ function freezeGeneration(pkg, generation) {
109
180
  : {}),
110
181
  });
111
182
  }
183
+ function clientBundleOf(pkg) {
184
+ return pkg[CLIENT_BUNDLE];
185
+ }
112
186
  function invalid(message, cause) {
113
187
  return new PluginPackageLoaderError('invalid_package', message, { cause });
114
188
  }
@@ -22,6 +22,7 @@ import { dirname, join, posix } from 'node:path';
22
22
  import { isCanonicalExtensionId } from '@maka/runtime/plugin-runtime';
23
23
  import { exportExtensionBundle, extensionPackageContentDigest, materializeExtensionPackage, } from './extension-bundle.js';
24
24
  import { EXTENSION_PACKAGE_MANIFEST_FILE, loadExtensionPackageManifest, } from './extension-package-manifest.js';
25
+ import { PLUGIN_CLIENT_BUNDLE_MAX_BYTES } from '../protocol/plugin-platform.js';
25
26
  const STORE_DIRECTORY = 'plugin-packages-v2';
26
27
  const MAX_FILES = 256;
27
28
  const MAX_FILE_BYTES = 8 * 1024 * 1024;
@@ -392,17 +393,32 @@ async function decodePackage(root, files) {
392
393
  const manifest = await loadExtensionPackageManifest(root);
393
394
  if (!manifest)
394
395
  throw invalid(`Plugin package is missing ${EXTENSION_PACKAGE_MANIFEST_FILE}`);
395
- if (!manifest.runtime?.entry)
396
- throw invalid('Plugin package has no trusted Runtime entry');
397
- if (!files.some((file) => file.path === manifest.runtime.entry)) {
396
+ if (!manifest.runtime?.entry && !manifest.client?.entry) {
397
+ throw invalid('Plugin package has no Runtime or Client entry');
398
+ }
399
+ if (manifest.runtime && !files.some((file) => file.path === manifest.runtime.entry)) {
398
400
  throw invalid(`Plugin Runtime entry does not exist: ${manifest.runtime.entry}`);
399
401
  }
402
+ if (manifest.client && !files.some((file) => file.path === manifest.client.entry)) {
403
+ throw invalid(`Plugin Client entry does not exist: ${manifest.client.entry}`);
404
+ }
405
+ if (manifest.client) {
406
+ const clientBytes = files.find((file) => file.path === manifest.client.entry)?.content
407
+ .byteLength;
408
+ if (clientBytes === 0) {
409
+ throw invalid(`Plugin Client entry is empty: ${manifest.client.entry}`);
410
+ }
411
+ if (clientBytes !== undefined && clientBytes > PLUGIN_CLIENT_BUNDLE_MAX_BYTES) {
412
+ throw invalid(`Plugin Client entry exceeds its size limit: ${manifest.client.entry}`);
413
+ }
414
+ }
400
415
  if (manifest.composition && !files.some((file) => file.path === manifest.composition.patch)) {
401
416
  throw invalid(`Plugin Composition patch does not exist: ${manifest.composition.patch}`);
402
417
  }
403
418
  return Object.freeze({
404
419
  manifest,
405
- entry: manifest.runtime.entry,
420
+ ...(manifest.runtime ? { entry: manifest.runtime.entry } : {}),
421
+ ...(manifest.client ? { clientEntry: manifest.client.entry } : {}),
406
422
  contentDigest: extensionPackageContentDigest(files),
407
423
  });
408
424
  }
@@ -501,7 +517,8 @@ function freezeInstalled(root, decoded) {
501
517
  extensionId: decoded.manifest.id,
502
518
  contentDigest: decoded.contentDigest,
503
519
  root,
504
- entry: join(root, ...decoded.entry.split('/')),
520
+ ...(decoded.entry ? { entry: join(root, ...decoded.entry.split('/')) } : {}),
521
+ ...(decoded.clientEntry ? { clientEntry: join(root, ...decoded.clientEntry.split('/')) } : {}),
505
522
  manifest: decoded.manifest,
506
523
  });
507
524
  }
@@ -17,8 +17,9 @@
17
17
  * under the License.
18
18
  */
19
19
  import { JsonArrayPageBudget } from './json-array-page-budget.js';
20
- import { createHash } from 'node:crypto';
20
+ import { createHash, randomUUID } from 'node:crypto';
21
21
  import { MakaPluginRuntimeError, } from '@maka/runtime/plugin-runtime';
22
+ import { PluginClientBridgeError, } from '@maka/runtime/plugin-client-bridge-service';
22
23
  import { PLUGIN_PLATFORM_QUERY_RESULT_MAX_BYTES } from '../protocol/plugin-platform.js';
23
24
  import { ExtensionBundleError } from './extension-bundle.js';
24
25
  import { ExtensionPackageManifestError } from './extension-package-manifest.js';
@@ -28,7 +29,14 @@ import { PluginPackageStoreError } from './plugin-package-store.js';
28
29
  import { HostPluginPlatformError } from './plugin-platform.js';
29
30
  export class HostPluginPlatformCoordinator {
30
31
  platform;
32
+ #streams = new Map();
33
+ #pendingStreamOpens = new Map();
31
34
  handlers = {
35
+ 'plugin.client.query': (input) => this.#client(input),
36
+ 'plugin.client.remote.call': (input, context) => this.#remoteCall(input, context),
37
+ 'plugin.client.remote.stream.open': (input, context) => this.#remoteStreamOpen(input, context),
38
+ 'plugin.client.remote.stream.next': (input, context) => this.#remoteStreamNext(input, context),
39
+ 'plugin.client.remote.stream.close': (input, context) => this.#remoteStreamClose(input, context),
32
40
  'plugin.platform.query': (input) => this.#query(input),
33
41
  'plugin.package.install': (input) => this.#install(input),
34
42
  'plugin.package.uninstall': (input) => this.#uninstall(input),
@@ -40,6 +48,109 @@ export class HostPluginPlatformCoordinator {
40
48
  constructor(platform) {
41
49
  this.platform = platform;
42
50
  }
51
+ releaseConnection(connectionId) {
52
+ for (const [streamId, stream] of this.#streams) {
53
+ if (stream.connectionId !== connectionId)
54
+ continue;
55
+ this.#streams.delete(streamId);
56
+ void stream.binding.close().catch(() => undefined);
57
+ }
58
+ }
59
+ async #remoteCall(input, context) {
60
+ try {
61
+ return {
62
+ ok: true,
63
+ result: { value: await this.platform.invokeClientRemote(input, context.inputClosedSignal) },
64
+ };
65
+ }
66
+ catch (error) {
67
+ return failure(error);
68
+ }
69
+ }
70
+ async #remoteStreamOpen(input, context) {
71
+ const connectionId = context.connectionId;
72
+ const active = [...this.#streams.values()].filter((stream) => stream.connectionId === connectionId).length;
73
+ const pending = this.#pendingStreamOpens.get(connectionId) ?? 0;
74
+ if (active + pending >= 32) {
75
+ return failed('operation_conflict', 'Plugin Client Remote stream limit reached');
76
+ }
77
+ this.#pendingStreamOpens.set(connectionId, pending + 1);
78
+ try {
79
+ const binding = await this.platform.openClientRemoteStream(input, context.inputClosedSignal);
80
+ const streamId = randomUUID();
81
+ this.#streams.set(streamId, { connectionId, binding, reading: false });
82
+ return { ok: true, result: { streamId } };
83
+ }
84
+ catch (error) {
85
+ return failure(error);
86
+ }
87
+ finally {
88
+ const remaining = (this.#pendingStreamOpens.get(connectionId) ?? 1) - 1;
89
+ if (remaining === 0)
90
+ this.#pendingStreamOpens.delete(connectionId);
91
+ else
92
+ this.#pendingStreamOpens.set(connectionId, remaining);
93
+ }
94
+ }
95
+ async #remoteStreamNext(input, context) {
96
+ const stream = this.#ownedStream(input.streamId, context.connectionId);
97
+ if (!stream)
98
+ return failed('not_found', 'Plugin Client Remote stream is unavailable');
99
+ if (stream.reading) {
100
+ return failed('operation_conflict', 'Plugin Client Remote stream already has an active pull');
101
+ }
102
+ stream.reading = true;
103
+ try {
104
+ const result = await stream.binding.next();
105
+ if (result.done) {
106
+ this.#streams.delete(input.streamId);
107
+ return { ok: true, result: { done: true } };
108
+ }
109
+ return { ok: true, result: { done: false, value: result.value } };
110
+ }
111
+ catch (error) {
112
+ this.#streams.delete(input.streamId);
113
+ await stream.binding.close().catch(() => undefined);
114
+ return failure(error);
115
+ }
116
+ finally {
117
+ stream.reading = false;
118
+ }
119
+ }
120
+ async #remoteStreamClose(input, context) {
121
+ // End-of-stream and generation retirement may have already released it.
122
+ // An existing stream remains strictly owned by its connection.
123
+ const stream = this.#streams.get(input.streamId);
124
+ if (!stream)
125
+ return { ok: true, result: { streamId: input.streamId } };
126
+ if (stream.connectionId !== context.connectionId)
127
+ return failed('not_found', 'Plugin Client Remote stream is unavailable');
128
+ this.#streams.delete(input.streamId);
129
+ try {
130
+ await stream.binding.close();
131
+ return { ok: true, result: { streamId: input.streamId } };
132
+ }
133
+ catch (error) {
134
+ return failure(error);
135
+ }
136
+ }
137
+ #ownedStream(streamId, connectionId) {
138
+ const stream = this.#streams.get(streamId);
139
+ return stream?.connectionId === connectionId ? stream : undefined;
140
+ }
141
+ async #client(input) {
142
+ try {
143
+ return {
144
+ ok: true,
145
+ result: await this.platform.read(async () => input.kind === 'snapshot'
146
+ ? this.platform.clientSnapshot()
147
+ : await this.platform.readClientBundle(input)),
148
+ };
149
+ }
150
+ catch (error) {
151
+ return failure(error);
152
+ }
153
+ }
43
154
  async #query(input) {
44
155
  try {
45
156
  return await this.platform.read(async () => {
@@ -210,6 +321,9 @@ function failure(error) {
210
321
  return failed('host_not_ready', error.message);
211
322
  if (error.code === 'stale_cursor')
212
323
  return failed('stale_cursor', error.message);
324
+ if (error.code === 'client_generation_conflict') {
325
+ return failed('operation_conflict', error.message);
326
+ }
213
327
  if (error.code === 'closed')
214
328
  return failed('host_draining', error.message);
215
329
  if (error.code === 'persistence_failed')
@@ -223,6 +337,13 @@ function failure(error) {
223
337
  return failure(error.cause);
224
338
  return failed('internal_failure', error.message);
225
339
  }
340
+ if (error instanceof PluginClientBridgeError) {
341
+ if (error.code === 'not_found')
342
+ return failed('not_found', error.message);
343
+ if (error.code === 'invalid_input')
344
+ return failed('invalid_request', error.message);
345
+ return failed('operation_conflict', error.message);
346
+ }
226
347
  if (error instanceof PluginPackageStoreError) {
227
348
  if (error.code === 'not_found')
228
349
  return failed('not_found', error.message);
@@ -17,13 +17,15 @@
17
17
  * under the License.
18
18
  */
19
19
  import { MakaCompositionLoader, } from '@maka/runtime/plugin-composition-loader';
20
+ import { createHash } from 'node:crypto';
20
21
  import { applyCompositionState, MakaPluginRuntimeError, } from '@maka/runtime/plugin-runtime';
21
22
  import { validateExtensionConfiguration } from './extension-package-manifest.js';
22
23
  import { recoverExtensionBundleImports } from './extension-bundle.js';
23
24
  import { loadPluginCompositionPatch } from './plugin-composition-patch.js';
24
25
  import { HostPluginCompositionStore, HostPluginCompositionStoreError, } from './plugin-composition-store.js';
25
- import { TrustedPluginPackageLoader } from './plugin-package-loader.js';
26
+ import { PluginPackageLoaderError, TrustedPluginPackageLoader } from './plugin-package-loader.js';
26
27
  import { PluginPackageStore, PluginPackageStoreError } from './plugin-package-store.js';
28
+ import { PLUGIN_CLIENT_BUNDLE_CHUNK_MAX_BYTES } from '../protocol/plugin-platform.js';
27
29
  export class HostPluginPlatformError extends Error {
28
30
  code;
29
31
  name = 'HostPluginPlatformError';
@@ -46,6 +48,7 @@ export class HostPluginPlatform {
46
48
  #systemPrompt;
47
49
  #commands;
48
50
  #executors;
51
+ #clientBridge;
49
52
  #authority = emptyCompositionAuthority();
50
53
  #desired = emptyCompositionState();
51
54
  #mutation = Promise.resolve();
@@ -70,6 +73,7 @@ export class HostPluginPlatform {
70
73
  this.#systemPrompt = options.systemPrompt;
71
74
  this.#commands = options.commands;
72
75
  this.#executors = options.executors;
76
+ this.#clientBridge = options.clientBridge;
73
77
  }
74
78
  async recover() {
75
79
  if (this.#recoveryStarted ||
@@ -413,6 +417,110 @@ export class HostPluginPlatform {
413
417
  }
414
418
  return Object.freeze(projections);
415
419
  }
420
+ async clientSnapshot() {
421
+ this.#assertReadable();
422
+ const entries = [];
423
+ const clientEntryIds = new Set();
424
+ for (const inspection of flattenEntryInspections(this.#composition.inspectTree('desktop-ui'))) {
425
+ clientEntryIds.add(inspection.id);
426
+ if (inspection.status !== 'active' ||
427
+ !inspection.packageId ||
428
+ inspection.generation === undefined) {
429
+ continue;
430
+ }
431
+ const pkg = this.#composition.package(inspection.packageId);
432
+ const bundle = this.#packageLoader.clientBundle(pkg);
433
+ if (!bundle)
434
+ continue;
435
+ const installed = await this.#packages.load(inspection.packageId);
436
+ entries.push(Object.freeze({
437
+ entryId: inspection.id,
438
+ extensionId: inspection.packageId,
439
+ generation: inspection.generation,
440
+ contentDigest: bundle.contentDigest,
441
+ clientDigest: bundle.clientDigest,
442
+ totalBytes: bundle.totalBytes,
443
+ dependencies: Object.freeze(installed.manifest.dependencies.map(({ id }) => id)),
444
+ ...(inspection.config === undefined
445
+ ? {}
446
+ : {
447
+ config: inspection.config,
448
+ }),
449
+ }));
450
+ }
451
+ const clientPackages = new Set(entries.map(({ extensionId }) => extensionId));
452
+ const failures = Object.freeze(this.#failures.filter((failure) => (failure.entryId !== undefined && clientEntryIds.has(failure.entryId)) ||
453
+ (failure.extensionId !== undefined && clientPackages.has(failure.extensionId))));
454
+ const revision = `sha256-${createHash('sha256')
455
+ .update(JSON.stringify({ authorityEpoch: this.#authority.generation, entries, failures }))
456
+ .digest('hex')}`;
457
+ return Object.freeze({
458
+ kind: 'snapshot',
459
+ authorityEpoch: this.#authority.generation,
460
+ revision,
461
+ entries: Object.freeze(entries),
462
+ failures,
463
+ });
464
+ }
465
+ async invokeClientRemote(input, signal) {
466
+ const execute = await this.read(async () => {
467
+ const target = await this.#verifyClientRemoteFence(input);
468
+ if (!this.#clientBridge) {
469
+ throw new PluginPackageLoaderError('not_found', 'Plugin Client Remote is unavailable');
470
+ }
471
+ return this.#clientBridge.prepareInvoke(target, input.method, input.input, signal);
472
+ });
473
+ return await execute();
474
+ }
475
+ async openClientRemoteStream(input, signal) {
476
+ const execute = await this.read(async () => {
477
+ const target = await this.#verifyClientRemoteFence(input);
478
+ if (!this.#clientBridge) {
479
+ throw new PluginPackageLoaderError('not_found', 'Plugin Client Remote is unavailable');
480
+ }
481
+ return this.#clientBridge.prepareOpen(target, input.method, input.input, signal);
482
+ });
483
+ return await execute();
484
+ }
485
+ async #verifyClientRemoteFence(fence) {
486
+ const snapshot = await this.clientSnapshot();
487
+ const entry = snapshot.entries.find(({ entryId }) => entryId === fence.entryId);
488
+ if (snapshot.authorityEpoch !== fence.authorityEpoch ||
489
+ snapshot.revision !== fence.revision ||
490
+ !entry ||
491
+ entry.extensionId !== fence.extensionId ||
492
+ entry.generation !== fence.generation ||
493
+ entry.contentDigest !== fence.contentDigest ||
494
+ entry.clientDigest !== fence.clientDigest) {
495
+ throw new HostPluginPlatformError('client_generation_conflict', `Plugin Client generation is stale: ${fence.extensionId}`);
496
+ }
497
+ return Object.freeze({
498
+ extensionId: fence.extensionId,
499
+ ...(fence.sessionId ? { sessionId: fence.sessionId } : {}),
500
+ });
501
+ }
502
+ async readClientBundle(input) {
503
+ this.#assertReadable();
504
+ const pkg = this.#composition.package(input.extensionId);
505
+ const bundle = this.#packageLoader.clientBundle(pkg);
506
+ if (!bundle ||
507
+ bundle.contentDigest !== input.contentDigest ||
508
+ bundle.clientDigest !== input.clientDigest) {
509
+ throw new PluginPackageLoaderError('not_found', `Plugin Client generation is stale or unavailable: ${input.extensionId}`);
510
+ }
511
+ const { content, totalBytes } = await this.#packageLoader.readClientBundle(pkg, input.offset, PLUGIN_CLIENT_BUNDLE_CHUNK_MAX_BYTES);
512
+ const nextOffset = input.offset + content.byteLength;
513
+ return Object.freeze({
514
+ kind: 'bundle',
515
+ extensionId: input.extensionId,
516
+ contentDigest: input.contentDigest,
517
+ clientDigest: input.clientDigest,
518
+ offset: input.offset,
519
+ totalBytes,
520
+ content: content.toString('base64'),
521
+ nextOffset: nextOffset < totalBytes ? nextOffset : null,
522
+ });
523
+ }
416
524
  async exportPackage(extensionId, targetPath) {
417
525
  await this.read(() => this.#packages.export(extensionId, targetPath));
418
526
  }
@@ -1002,6 +1110,17 @@ function compositionAuthority(generation, packageLayers, overlays) {
1002
1110
  overlays: Object.freeze(structuredClone(overlays)),
1003
1111
  });
1004
1112
  }
1113
+ function flattenEntryInspections(entries) {
1114
+ const flattened = [];
1115
+ const visit = (items) => {
1116
+ for (const item of items) {
1117
+ flattened.push(item);
1118
+ visit(item.children);
1119
+ }
1120
+ };
1121
+ visit(entries);
1122
+ return flattened;
1123
+ }
1005
1124
  function compositionEntries(state) {
1006
1125
  const walk = (entries) => entries.flatMap((entry) => [entry, ...walk(entry.children ?? [])]);
1007
1126
  return [
@@ -0,0 +1,92 @@
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 { MAX_ATTACHMENT_BYTES } from '@maka/core/attachments';
20
+ function refused(reason, message) {
21
+ return { ok: false, reason, message };
22
+ }
23
+ /**
24
+ * What a material must be before it is brought into the asking Session.
25
+ *
26
+ * Recall has already decided the Session may be seen; this decides the
27
+ * artifact inside it may be taken. `material_id` is model-influenced input, so
28
+ * this is the boundary that keeps a recalled name from becoming a way to read
29
+ * any artifact in the workspace.
30
+ *
31
+ * Only a file a person attached: a tool result, a projection, or an archive is
32
+ * not material a user shared, and copying one would spend storage on a file
33
+ * the model was never offered. Only one `Read` can answer, since a copy it
34
+ * cannot decode is a failed call bought at the price of storing the bytes
35
+ * twice. A refusal reads as "not found" wherever the caller should not learn
36
+ * the difference between an artifact that is not there and one it may not
37
+ * have.
38
+ */
39
+ export function createRecallMaterialFetch(deps) {
40
+ return async ({ sourceSessionId, materialId, targetSessionId, abortSignal }) => {
41
+ if (abortSignal?.aborted)
42
+ return refused('not_found', 'Aborted.');
43
+ const record = await deps.artifacts
44
+ .getInSession(sourceSessionId, materialId)
45
+ .then((entry) => entry.record)
46
+ .catch(() => null);
47
+ if (!record || record.source !== 'user_upload') {
48
+ return refused('not_found', 'That material was not found.');
49
+ }
50
+ if (record.kind === 'pdf') {
51
+ return refused('unsupported', 'PDF materials cannot be decoded.');
52
+ }
53
+ if (record.sizeBytes > MAX_ATTACHMENT_BYTES) {
54
+ return refused('unsupported', 'That material is too large to bring into this Session.');
55
+ }
56
+ const signal = abortSignal ?? new AbortController().signal;
57
+ // A store read or a copy can throw on state that changed under us — the
58
+ // source purged between the check and the copy, a payload deleted after
59
+ // ingest, an abort landing mid-write. The caller is a tool, so those have
60
+ // to arrive as a refusal it can report rather than as an unhandled error.
61
+ try {
62
+ // Already here: answer it without making a second copy of itself.
63
+ if (sourceSessionId === targetSessionId) {
64
+ return {
65
+ ok: true,
66
+ content: await deps.attachments.readAttachmentResource(targetSessionId, materialId, signal),
67
+ };
68
+ }
69
+ // The copy id is derived from the two Sessions and the source id, so
70
+ // opening the same material again reuses the copy rather than adding
71
+ // one. `reuse_verified` is what lets the second open succeed.
72
+ const copied = await deps.artifacts.copyConversationArtifacts({
73
+ sourceSessionId,
74
+ targetSessionId,
75
+ turnIds: [],
76
+ includeArtifactIds: [materialId],
77
+ existingTarget: 'reuse_verified',
78
+ });
79
+ const copiedId = copied.artifactIds.get(materialId);
80
+ if (!copiedId) {
81
+ return refused('not_found', 'That material could not be brought into this Session.');
82
+ }
83
+ return {
84
+ ok: true,
85
+ content: await deps.attachments.readAttachmentResource(targetSessionId, copiedId, signal),
86
+ };
87
+ }
88
+ catch {
89
+ return refused('not_found', 'That material could not be read.');
90
+ }
91
+ };
92
+ }
@@ -1487,7 +1487,11 @@ export class RootTurnCoordinator {
1487
1487
  commit: async () => ({ ok: true }),
1488
1488
  };
1489
1489
  }
1490
- startTurnResume(input, context) {
1490
+ /** Internal composition seam for checks that must share fresh continuation admission. */
1491
+ startTurnResumeWithValidation(input, context, beforeFreshAdmission) {
1492
+ return this.startTurnResume(input, context, beforeFreshAdmission);
1493
+ }
1494
+ startTurnResume(input, context, beforeFreshAdmission) {
1491
1495
  if (isWorkHubCoordinationSessionId(input.sessionId)) {
1492
1496
  return Promise.resolve(operationUnavailable(WORKHUB_COORDINATION_EXECUTION_UNAVAILABLE_REASON));
1493
1497
  }
@@ -1564,6 +1568,15 @@ export class RootTurnCoordinator {
1564
1568
  reservation ??= this.takeParkedContinuationReservation(existing);
1565
1569
  return this.prepareAdmittedTurn(turnInput, existing, context.acquireResidency, lease, undefined, undefined, reservation, reconstructed.continuation);
1566
1570
  }
1571
+ try {
1572
+ await beforeFreshAdmission?.();
1573
+ }
1574
+ catch (error) {
1575
+ return {
1576
+ kind: 'complete',
1577
+ outcome: operationConflict(errorMessage(error)),
1578
+ };
1579
+ }
1567
1580
  reservation ??= this.reserveRootTurn(input.sessionId);
1568
1581
  if (!reservation) {
1569
1582
  return {