maka-agent 0.2.0-dev.41.20260918 → 0.2.0-dev.43.20260919

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 (54) hide show
  1. package/LICENSE +7 -4
  2. package/dist/acp/maka-acp-agent.js +17 -6
  3. package/dist/acp/session-event-mapper.js +6 -0
  4. package/dist/acp/session-interactions.js +520 -0
  5. package/dist/acp/session-registry.js +80 -9
  6. package/dist/acp/tool-event-mapper.js +60 -2
  7. package/dist/pi-tui-runner.js +57 -6
  8. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  9. package/node_modules/@maka/core/dist/client-plugin-bridge.js +19 -0
  10. package/node_modules/@maka/core/dist/connection-usage.js +27 -0
  11. package/node_modules/@maka/core/dist/events.js +58 -7
  12. package/node_modules/@maka/core/dist/external-session.js +4 -3
  13. package/node_modules/@maka/core/dist/interaction.js +38 -4
  14. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  15. package/node_modules/@maka/core/dist/model-metadata.js +89 -0
  16. package/node_modules/@maka/core/dist/provider-auth.js +9 -1
  17. package/node_modules/@maka/core/dist/recall.js +198 -15
  18. package/node_modules/@maka/core/dist/redaction.js +8 -0
  19. package/node_modules/@maka/core/dist/session-reference.js +149 -0
  20. package/node_modules/@maka/core/dist/skill-locations.js +29 -0
  21. package/node_modules/@maka/core/package.json +4 -0
  22. package/node_modules/@maka/runtime/dist/commandcode-cli-language-model.js +27 -3
  23. package/node_modules/@maka/runtime/dist/connection-usage.js +232 -0
  24. package/node_modules/@maka/runtime/dist/model-factory.js +5 -3
  25. package/node_modules/@maka/runtime/dist/model-history.js +13 -2
  26. package/node_modules/@maka/runtime/dist/plugin-client-bridge-service.js +308 -0
  27. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +4 -3
  28. package/node_modules/@maka/runtime/dist/plugin-data-services.js +3 -3
  29. package/node_modules/@maka/runtime/dist/recall-tools.js +70 -2
  30. package/node_modules/@maka/runtime/dist/skills-discovery.js +17 -23
  31. package/node_modules/@maka/runtime/package.json +2 -0
  32. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +132 -1
  33. package/node_modules/@maka/runtime-host/dist/protocol/index.js +11 -1
  34. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +6 -0
  35. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +269 -0
  36. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +2 -0
  37. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +57 -1
  38. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +50 -9
  39. package/node_modules/@maka/runtime-host/dist/server/extension-package-manifest.js +19 -1
  40. package/node_modules/@maka/runtime-host/dist/server/plugin-package-loader.js +88 -14
  41. package/node_modules/@maka/runtime-host/dist/server/plugin-package-store.js +22 -5
  42. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +122 -1
  43. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +120 -1
  44. package/node_modules/@maka/runtime-host/dist/server/recall-material-fetch.js +92 -0
  45. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +14 -1
  46. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +17 -1
  47. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +67 -3
  48. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +9 -3
  49. package/node_modules/@maka/runtime-host/dist/server/workhub-target-execution-authority.js +161 -0
  50. package/node_modules/@maka/storage/dist/codex-session-adapter.js +26 -28
  51. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +34 -1
  52. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -0
  53. package/node_modules/@maka/storage/dist/session-store.js +5 -2
  54. package/package.json +1 -1
@@ -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');
@@ -23,7 +23,8 @@ import { isDeepStrictEqual } from 'node:util';
23
23
  import { normalizeMessageContent } from '@maka/core/events';
24
24
  import { WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_SESSION_ROLE, WORKHUB_COORDINATION_REPLACEMENT_SCHEMA_VERSION, WORKHUB_COORDINATION_STOP_SCHEMA_VERSION, isWorkHubCoordinationSession, isWorkHubCoordinationSessionId, } from '@maka/core/session';
25
25
  import { WORKHUB_COORDINATION_TEXT_MAX_BYTES } from '../protocol/index.js';
26
- import { SessionOperationFailure, projectSessionCatalogRecord, } from './session-catalog-coordinator.js';
26
+ import { WORKHUB_COORDINATION_DEFAULT_MODEL_REQUIRED_MESSAGE, } from '../protocol/workhub-coordination.js';
27
+ import { SessionOperationFailure, WorkHubDefaultModelRequiredError, projectSessionCatalogRecord, } from './session-catalog-coordinator.js';
27
28
  import { RuntimeInteractionAdmissionRejectedError, RuntimeInteractionFailStopError, } from '@maka/runtime/interaction-authority';
28
29
  import { WorkHubActionEffectFailure, WorkHubActionGateFailure, WorkHubCoordinationActionGate, } from './workhub-coordination-action-gate.js';
29
30
  const CREATE_FINGERPRINT = `sha256:${createHash('sha256')
@@ -82,6 +83,7 @@ export class HostWorkHubCoordinationCoordinator {
82
83
  this.#requestDrain = options.requestDrain;
83
84
  this.#actionGate = new WorkHubCoordinationActionGate({
84
85
  listSessions: () => this.#stores.listHeaders(),
86
+ ...(options.targetExecution ? { targetExecution: options.targetExecution } : {}),
85
87
  // The global action owner is committed under the same Coordination
86
88
  // admission that serializes every durable Coordination fact, so a
87
89
  // concurrent action cannot slip between the claim and the fact it owns.
@@ -109,7 +111,7 @@ export class HostWorkHubCoordinationCoordinator {
109
111
  resume: async (input, context) => ({
110
112
  disposition: 'resume_work',
111
113
  targetSessionId: input.source.targetSessionId,
112
- ...(await options.sessionActions.resumeDelegation(input.source, context, input.actionId, input.validateFreshTarget)),
114
+ ...(await options.sessionActions.resumeDelegation(input.source, context, input.actionId, input.validateFreshTarget, input.prepareTargetExecution, input.assertTargetExecutionReady)),
113
115
  }),
114
116
  });
115
117
  }
@@ -516,6 +518,7 @@ export class HostWorkHubCoordinationCoordinator {
516
518
  result: await this.#actionGate.act({
517
519
  ...action,
518
520
  ...(selectedTarget ? { selectedTarget } : {}),
521
+ coordinationRunId: request.runId,
519
522
  userText: request.content.text,
520
523
  ...(carriesAttachments && request.content.attachments
521
524
  ? { attachments: request.content.attachments }
@@ -806,10 +809,13 @@ export class HostWorkHubCoordinationCoordinator {
806
809
  }
807
810
  /** Keeps a model-authority gap distinguishable from a failed authority read. */
808
811
  function createTargetFailure(error) {
812
+ if (error instanceof WorkHubDefaultModelRequiredError) {
813
+ return failure('model_required', WORKHUB_COORDINATION_DEFAULT_MODEL_REQUIRED_MESSAGE);
814
+ }
809
815
  if (error instanceof SessionOperationFailure && error.code === 'persistence_failed') {
810
816
  return failure('persistence_failed', error.message);
811
817
  }
812
- return failure('operation_conflict', 'WorkHub Coordination Session requires an available default model');
818
+ return failure('operation_conflict', 'WorkHub Coordination Session target is unavailable');
813
819
  }
814
820
  function validCoordinationIdentityHeader(header) {
815
821
  return (isWorkHubCoordinationSessionId(header.id) &&
@@ -0,0 +1,161 @@
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 { createHash } from 'node:crypto';
20
+ import { authorizeConnectionModel, connectionModelChoiceValue, connectionEnabledModelIds, } from '@maka/core/llm-connections';
21
+ import { isModelExplicitlyUnsupportedForChat } from '@maka/core/model-catalog';
22
+ import { thinkingVariantsForConnection } from '@maka/core/model-thinking';
23
+ import { WORKHUB_COORDINATION_SESSION_ID } from '@maka/core/session';
24
+ import { WorkHubActionEffectFailure } from './workhub-coordination-action-gate.js';
25
+ /** Keeps target-model repair behind one Host-owned interface used by every WorkHub execution path. */
26
+ export class HostWorkHubTargetExecutionAuthority {
27
+ #options;
28
+ constructor(options) {
29
+ this.#options = options;
30
+ }
31
+ async prepare(input, context) {
32
+ const rejectedSelections = [];
33
+ for (let attempt = 0; attempt < 3; attempt++) {
34
+ const readiness = await this.#readiness(input.targetSessionId);
35
+ if (readiness.kind === 'ready')
36
+ return;
37
+ if (readiness.replacements.length === 0) {
38
+ throw new WorkHubActionEffectFailure('operation_unavailable', `Task “${input.targetSessionName}” has no enabled replacement model`);
39
+ }
40
+ const requestId = createHash('sha256')
41
+ .update(JSON.stringify({
42
+ kind: 'workhub_target_model_repair_v1',
43
+ actionId: input.actionId,
44
+ coordinationRunId: input.coordinationRunId,
45
+ targetSessionId: input.targetSessionId,
46
+ revision: readiness.record.revision,
47
+ replacements: readiness.replacements.map(({ value }) => value),
48
+ rejectedSelections,
49
+ }))
50
+ .digest('hex');
51
+ const choice = await this.#options.requestForm({
52
+ sessionId: WORKHUB_COORDINATION_SESSION_ID,
53
+ turnId: input.coordinationTurnId,
54
+ runId: input.coordinationRunId,
55
+ requestId,
56
+ create: async () => ({
57
+ kind: 'form',
58
+ toolUseId: input.actionId,
59
+ message: rejectedSelections.length === 0
60
+ ? `Task “${input.targetSessionName}” uses model “${readiness.record.header.model}”, which is no longer available. Choose a replacement to continue.`
61
+ : `The selected model cannot currently run task “${input.targetSessionName}”. Choose another model to continue.`,
62
+ requester: { name: 'WorkHub' },
63
+ fields: [
64
+ {
65
+ kind: 'string',
66
+ name: 'targetModel',
67
+ label: `Model for ${input.targetSessionName}`,
68
+ required: true,
69
+ presentation: 'model_picker',
70
+ minLength: 1,
71
+ },
72
+ ],
73
+ }),
74
+ });
75
+ if (choice.answer.action !== 'accept') {
76
+ throw new WorkHubActionEffectFailure('operation_conflict', `Model update for task “${input.targetSessionName}” was cancelled`);
77
+ }
78
+ const value = choice.answer.values.targetModel;
79
+ const replacement = readiness.replacements.find(({ value: offered }) => offered === value);
80
+ if (!replacement) {
81
+ if (typeof value === 'string')
82
+ rejectedSelections.push(value);
83
+ continue;
84
+ }
85
+ const updated = await this.#options.updateModel({
86
+ sessionId: input.targetSessionId,
87
+ expectedRevision: readiness.record.revision,
88
+ modelTarget: replacement.target,
89
+ }, context);
90
+ if (updated === 'committed') {
91
+ if ((await this.#readiness(input.targetSessionId)).kind === 'ready')
92
+ return;
93
+ }
94
+ }
95
+ throw new WorkHubActionEffectFailure('operation_conflict', rejectedSelections.length > 0
96
+ ? 'No executable replacement model was selected for this task'
97
+ : 'Task model changed while WorkHub was preparing the delegation; try again');
98
+ }
99
+ async assertReady(targetSessionId) {
100
+ const readiness = await this.#readiness(targetSessionId);
101
+ if (readiness.kind !== 'ready') {
102
+ throw new WorkHubActionEffectFailure('operation_conflict', 'Target task model is no longer enabled; choose a replacement and try again');
103
+ }
104
+ }
105
+ async #readiness(targetSessionId) {
106
+ const record = await this.#options.readSession(targetSessionId);
107
+ const header = record.header;
108
+ if (header.backend === 'plugin-executor')
109
+ return { kind: 'ready' };
110
+ const resolved = await this.#options.runtimePolicy.resolveExecutionConnection(header.llmConnectionId === undefined
111
+ ? { kind: 'catalog_slug', connectionSlug: header.llmConnectionSlug }
112
+ : {
113
+ kind: 'bound',
114
+ connectionId: header.llmConnectionId,
115
+ connectionSlug: header.llmConnectionSlug,
116
+ });
117
+ if (resolved.kind === 'ready') {
118
+ const current = authorizeConnectionModel(resolved.connection, header.model);
119
+ if (current && !isModelExplicitlyUnsupportedForChat(current))
120
+ return { kind: 'ready' };
121
+ }
122
+ const catalog = await this.#options.runtimePolicy.connectionCatalog.getSnapshot();
123
+ const resolvedConnections = await Promise.all(catalog.connections.map((connection) => this.#options.runtimePolicy.resolveExecutionConnection({
124
+ kind: 'bound',
125
+ connectionId: connection.connectionId,
126
+ connectionSlug: connection.slug,
127
+ })));
128
+ const replacements = resolvedConnections
129
+ .flatMap((candidate) => {
130
+ if (candidate.kind !== 'ready')
131
+ return [];
132
+ const connection = candidate.connection;
133
+ return connectionEnabledModelIds(connection).flatMap((modelId) => {
134
+ const model = authorizeConnectionModel(connection, modelId);
135
+ if (!model || isModelExplicitlyUnsupportedForChat(model))
136
+ return [];
137
+ if (header.thinkingLevel !== undefined &&
138
+ !thinkingVariantsForConnection({
139
+ providerType: connection.providerType,
140
+ modelOverrides: connection.modelOverrides,
141
+ }, modelId).includes(header.thinkingLevel)) {
142
+ return [];
143
+ }
144
+ const target = {
145
+ kind: 'explicit',
146
+ connectionId: connection.connectionId,
147
+ connectionSlug: connection.slug,
148
+ model: modelId,
149
+ };
150
+ return [
151
+ {
152
+ value: connectionModelChoiceValue(target.connectionId, target.connectionSlug, target.model),
153
+ target,
154
+ },
155
+ ];
156
+ });
157
+ })
158
+ .sort((left, right) => left.value.localeCompare(right.value));
159
+ return { kind: 'model_repair_required', record, replacements };
160
+ }
161
+ }