maka-agent 0.2.0-dev.41.20260918 → 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 (35) hide show
  1. package/LICENSE +7 -4
  2. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  3. package/node_modules/@maka/core/dist/client-plugin-bridge.js +19 -0
  4. package/node_modules/@maka/core/dist/events.js +58 -7
  5. package/node_modules/@maka/core/dist/interaction.js +38 -4
  6. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  7. package/node_modules/@maka/core/dist/model-metadata.js +89 -0
  8. package/node_modules/@maka/core/dist/recall.js +198 -15
  9. package/node_modules/@maka/core/dist/redaction.js +8 -0
  10. package/node_modules/@maka/core/dist/session-reference.js +149 -0
  11. package/node_modules/@maka/core/package.json +2 -0
  12. package/node_modules/@maka/runtime/dist/model-factory.js +5 -3
  13. package/node_modules/@maka/runtime/dist/model-history.js +13 -2
  14. package/node_modules/@maka/runtime/dist/plugin-client-bridge-service.js +308 -0
  15. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +4 -3
  16. package/node_modules/@maka/runtime/dist/plugin-data-services.js +3 -3
  17. package/node_modules/@maka/runtime/dist/recall-tools.js +70 -2
  18. package/node_modules/@maka/runtime/package.json +1 -0
  19. package/node_modules/@maka/runtime-host/dist/protocol/index.js +7 -1
  20. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +5 -0
  21. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +269 -0
  22. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +2 -0
  23. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +46 -6
  24. package/node_modules/@maka/runtime-host/dist/server/extension-package-manifest.js +19 -1
  25. package/node_modules/@maka/runtime-host/dist/server/plugin-package-loader.js +88 -14
  26. package/node_modules/@maka/runtime-host/dist/server/plugin-package-store.js +22 -5
  27. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +122 -1
  28. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +120 -1
  29. package/node_modules/@maka/runtime-host/dist/server/recall-material-fetch.js +92 -0
  30. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +14 -1
  31. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +17 -1
  32. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +67 -3
  33. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +9 -3
  34. package/node_modules/@maka/runtime-host/dist/server/workhub-target-execution-authority.js +161 -0
  35. package/package.json +1 -1
@@ -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 {
@@ -56,6 +56,13 @@ export class NoUsableImportModelError extends SessionOperationFailure {
56
56
  this.name = 'NoUsableImportModelError';
57
57
  }
58
58
  }
59
+ /** The WorkHub bootstrap path has no executable default selected by the user. */
60
+ export class WorkHubDefaultModelRequiredError extends SessionOperationFailure {
61
+ constructor(message) {
62
+ super('operation_unavailable', message);
63
+ this.name = 'WorkHubDefaultModelRequiredError';
64
+ }
65
+ }
59
66
  /**
60
67
  * Connection+model candidates for an imported task, most-preferred first: the
61
68
  * configured default (kept at its exact precedence), then one ready model per
@@ -176,7 +183,16 @@ export class HostSessionCatalogCoordinator {
176
183
  * action.
177
184
  */
178
185
  async resolveDefaultCreateTarget() {
179
- return this.#composeCreateTarget(this.#resolveModel({ kind: 'default' }, undefined));
186
+ try {
187
+ return await this.#composeCreateTarget(this.#resolveModel({ kind: 'default' }, undefined));
188
+ }
189
+ catch (error) {
190
+ if (error instanceof SessionOperationFailure &&
191
+ (error.code === 'operation_unavailable' || error.code === 'invalid_request')) {
192
+ throw new WorkHubDefaultModelRequiredError(error.message);
193
+ }
194
+ throw error;
195
+ }
180
196
  }
181
197
  async #composeCreateTarget(modelResolution) {
182
198
  const [model, policy] = await Promise.all([modelResolution, this.#readRuntimePolicy()]);
@@ -70,7 +70,7 @@ export class WorkHubCoordinationActionGate {
70
70
  return Promise.reject(new WorkHubActionGateFailure('action_conflict', 'WorkHub creation title is empty'));
71
71
  }
72
72
  const fingerprint = actionFingerprint(input);
73
- const requestFingerprint = digest(input);
73
+ const requestFingerprint = actionRequestFingerprint(input);
74
74
  const replay = this.#actions.get(input.actionId);
75
75
  if (replay) {
76
76
  if (replay.requestFingerprint !== requestFingerprint) {
@@ -179,7 +179,18 @@ export class WorkHubCoordinationActionGate {
179
179
  if (!target.sessionName)
180
180
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub resume target is unavailable');
181
181
  };
182
- return this.#effects.resume({ actionId: input.actionId, source, validateFreshTarget }, context);
182
+ const preparation = this.#targetExecutionPreparation(input, source.targetSessionId, source.targetSessionName).targetExecutionPreparation;
183
+ return this.#effects.resume({
184
+ actionId: input.actionId,
185
+ source,
186
+ validateFreshTarget,
187
+ ...(preparation && this.#effects.targetExecution
188
+ ? {
189
+ prepareTargetExecution: () => this.#effects.targetExecution.prepare(preparation, context),
190
+ assertTargetExecutionReady: () => this.#effects.targetExecution.assertReady(source.targetSessionId),
191
+ }
192
+ : {}),
193
+ }, context);
183
194
  }
184
195
  if ('disposition' in proposal && proposal.disposition === 'create_new') {
185
196
  if (!input.create) {
@@ -205,10 +216,14 @@ export class WorkHubCoordinationActionGate {
205
216
  }
206
217
  await this.#assertReplacementReplayTarget(input, prepared.targetSessionId);
207
218
  await this.#claimAction(prepared.actionId, 'replace', prepared.actionFingerprint, prepared.replacesDelegationId);
219
+ await this.#prepareTargetExecution({
220
+ ...this.#targetExecutionPreparation(input, prepared.targetSessionId, prepared.targetSessionName),
221
+ }, context);
208
222
  return this.#replace(prepared, context);
209
223
  }
210
224
  const replacement = await this.#replacementAssignment(input, replaced);
211
225
  await this.#claimAction(replacement.actionId, 'replace', replacement.actionFingerprint, replacement.replacesDelegationId);
226
+ await this.#prepareTargetExecution(replacement, context);
212
227
  const intent = await this.#effects.prepareReplacement(replacement);
213
228
  return this.#replace(intent, context);
214
229
  }
@@ -226,6 +241,7 @@ export class WorkHubCoordinationActionGate {
226
241
  this.#assertTarget(target);
227
242
  return this.#assign({
228
243
  ...delegationAssignment(input, fingerprint, target.sessionId, target.sessionName),
244
+ ...this.#targetExecutionPreparation(input, target.sessionId, target.sessionName),
229
245
  ...(input.selectedTarget
230
246
  ? {
231
247
  validateFreshTarget: async () => {
@@ -415,6 +431,7 @@ export class WorkHubCoordinationActionGate {
415
431
  replacesDelegationId: replaced.delegationId,
416
432
  replacedTargetSessionId: replaced.targetSessionId,
417
433
  replacedTargetMessageId: replaced.targetMessageId,
434
+ ...this.#targetExecutionPreparation(input, destination.sessionId, destination.sessionName),
418
435
  };
419
436
  }
420
437
  async #replace(replacement, context) {
@@ -530,7 +547,14 @@ export class WorkHubCoordinationActionGate {
530
547
  }
531
548
  async #assign(assignment, context) {
532
549
  await this.#claimAction(assignment.actionId, assignment.replacesDelegationId ? 'replace' : assignment.disposition, assignment.actionFingerprint, assignment.replacesDelegationId ?? assignment.targetSessionId);
533
- const admitted = await this.#effects.assign(assignment, context);
550
+ await this.#prepareTargetExecution(assignment, context);
551
+ const validateFreshTarget = assignment.disposition === 'delegate_existing' && this.#effects.targetExecution
552
+ ? async () => {
553
+ await assignment.validateFreshTarget?.();
554
+ await this.#effects.targetExecution.assertReady(assignment.targetSessionId);
555
+ }
556
+ : assignment.validateFreshTarget;
557
+ const admitted = await this.#effects.assign(validateFreshTarget ? { ...assignment, validateFreshTarget } : assignment, context);
534
558
  if (assignment.replacesDelegationId) {
535
559
  return {
536
560
  disposition: 'replace',
@@ -555,6 +579,39 @@ export class WorkHubCoordinationActionGate {
555
579
  throw new WorkHubActionGateFailure('target_waiting_for_user', 'Target Session is waiting for user input');
556
580
  }
557
581
  }
582
+ #targetExecutionPreparation(input, targetSessionId, targetSessionName) {
583
+ return input.coordinationTurnId && input.coordinationRunId
584
+ ? {
585
+ targetExecutionPreparation: {
586
+ actionId: input.actionId,
587
+ coordinationTurnId: input.coordinationTurnId,
588
+ coordinationRunId: input.coordinationRunId,
589
+ targetSessionId,
590
+ targetSessionName,
591
+ },
592
+ }
593
+ : {};
594
+ }
595
+ async #prepareTargetExecution(input, context) {
596
+ const authority = this.#effects.targetExecution;
597
+ const preparation = input.targetExecutionPreparation ??
598
+ (input.actionId &&
599
+ input.targetSessionId &&
600
+ input.targetSessionName &&
601
+ input.coordinationTurnId &&
602
+ input.coordinationRunId
603
+ ? {
604
+ actionId: input.actionId,
605
+ targetSessionId: input.targetSessionId,
606
+ targetSessionName: input.targetSessionName,
607
+ coordinationTurnId: input.coordinationTurnId,
608
+ coordinationRunId: input.coordinationRunId,
609
+ }
610
+ : undefined);
611
+ if (!authority || !preparation || !context)
612
+ return;
613
+ await authority.prepare(preparation, context);
614
+ }
558
615
  #boundReplays() {
559
616
  while (this.#actions.size > ACTION_REPLAY_MAX_ITEMS) {
560
617
  const oldest = this.#actions.keys().next().value;
@@ -688,6 +745,13 @@ function actionFingerprint(input) {
688
745
  disposition: proposal.operation === 'stop' ? 'stop_work' : 'resume_work',
689
746
  });
690
747
  }
748
+ function actionRequestFingerprint(input) {
749
+ // Coordination execution identity changes when the Host retries the same
750
+ // durable action after a process failure. It authorizes where a repair Form
751
+ // is shown, but is not part of the user's proposal or replay identity.
752
+ const { coordinationRunId: _coordinationRunId, ...proposal } = input;
753
+ return digest(proposal);
754
+ }
691
755
  function replacementActionFingerprint(input, targetSessionId) {
692
756
  if (!('operation' in input.proposal) || input.proposal.operation !== 'correct') {
693
757
  throw new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub replacement replay');