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
@@ -19,12 +19,13 @@
19
19
  import { createHash } from 'node:crypto';
20
20
  import { userInfo } from 'node:os';
21
21
  import { isActiveShellRunStatus } from '@maka/core/shell-run';
22
+ import { shellRunStateProjection } from '@maka/core/shell-run-result';
22
23
  import { ShellRunPtyControlClosedError, isShellRunResourceRef, } from '@maka/runtime/shell-run-contract';
23
24
  import { defaultShellPlan, ShellPreferenceError } from '@maka/runtime/shell-detect';
24
25
  import { isSessionNotFoundError } from '@maka/storage/execution-stores';
25
26
  import { decodeRuntimeResourceControllerAcquireResult, decodeRuntimeResourceControllerControlResult, decodeRuntimeResourceQueryResult, decodeRuntimeResourceStopResult, decodeRuntimeResourceStartResult, RUNTIME_RESOURCE_CONTROLLER_ACQUIRE_RESULT_MAX_BYTES, RUNTIME_RESOURCE_MAX_CONTROL_SEQUENCE, } from '../protocol/index.js';
26
27
  import { boundedFailureDiagnostic } from './failure-diagnostic.js';
27
- import { boundedRuntimeResourceSnapshot, canonicalRuntimeResources, createRuntimeResourcePage, runtimeResourceRevision, runtimeResourceSnapshotFromResult, } from './runtime-resource-projection.js';
28
+ import { boundedRuntimeResourceState, canonicalRuntimeResources, createRuntimeResourcePage, runtimeResourceRevision, } from './runtime-resource-projection.js';
28
29
  const MAX_CONTROL_REPLAYS = 128;
29
30
  /** Owns Host Shell/PTY tools plus the connection-scoped Client controller fence. */
30
31
  export class HostRuntimeResourceCoordinator {
@@ -347,22 +348,22 @@ export class HostRuntimeResourceCoordinator {
347
348
  return {
348
349
  ok: true,
349
350
  result: decodeRuntimeResourceStartResult({
350
- resource: boundedRuntimeResourceSnapshot(await this.#manager.inspectResource(input.sessionId, launched.ref)),
351
+ resource: boundedRuntimeResourceState(shellRunStateProjection(launched)),
351
352
  }),
352
353
  };
353
354
  }
354
- catch (inspectError) {
355
+ catch (replyError) {
355
356
  // The command is already live but the operation must not report a
356
357
  // success it cannot honor: stop it so a client retry cannot
357
358
  // double-execute (#3210 review). Best-effort — the surfaced error
358
- // stays the inspection failure.
359
+ // stays the reply failure.
359
360
  try {
360
361
  await this.#manager.stopBackgroundTask(input.sessionId, launched.ref, new AbortController().signal, 'client');
361
362
  }
362
363
  catch {
363
- /* keep the inspection failure as the surfaced cause */
364
+ /* keep the reply failure as the surfaced cause */
364
365
  }
365
- throw inspectError;
366
+ throw replyError;
366
367
  }
367
368
  });
368
369
  }
@@ -388,8 +389,11 @@ export class HostRuntimeResourceCoordinator {
388
389
  if (sessionFailure)
389
390
  return mutationFailure('runtime.resource.controller.acquire', sessionFailure);
390
391
  try {
391
- const snapshot = await this.#manager.inspectResource(input.sessionId, input.ref);
392
- if (snapshot.mode !== 'pty' || !isActiveShellRunStatus(snapshot.status)) {
392
+ const pty = this.#manager.getLivePtySnapshot(input.sessionId, input.ref);
393
+ if (!pty) {
394
+ // No live handle: read through the manager so a stale active record
395
+ // is repaired to orphaned; the reply is a conflict either way.
396
+ await this.#manager.inspectResource(input.sessionId, input.ref);
393
397
  return mutationFailure('runtime.resource.controller.acquire', {
394
398
  code: 'operation_conflict',
395
399
  message: 'Only an active PTY Runtime Resource can be controlled',
@@ -420,14 +424,6 @@ export class HostRuntimeResourceCoordinator {
420
424
  };
421
425
  this.#controllers.set(key, controller);
422
426
  this.#controllerResources.set(identity, key);
423
- const pty = this.#manager.getLivePtySnapshot(input.sessionId, input.ref);
424
- if (!pty) {
425
- this.#releaseController(key);
426
- return mutationFailure('runtime.resource.controller.acquire', {
427
- code: 'operation_conflict',
428
- message: 'Runtime Resource PTY is no longer available',
429
- });
430
- }
431
427
  return {
432
428
  ok: true,
433
429
  result: boundedControllerAcquireResult(controller.controllerId, controller.nextSequence, pty),
@@ -485,7 +481,6 @@ export class HostRuntimeResourceCoordinator {
485
481
  const result = decodeRuntimeResourceControllerControlResult({
486
482
  controllerId: input.controllerId,
487
483
  sequence: input.sequence,
488
- resource: boundedRuntimeResourceSnapshot(runtimeResourceSnapshotFromResult(controlled)),
489
484
  });
490
485
  this.#rememberReplay({
491
486
  connectionId: context.connectionId,
@@ -555,12 +550,7 @@ export class HostRuntimeResourceCoordinator {
555
550
  try {
556
551
  const result = await this.#manager.stopBackgroundTask(input.sessionId, input.ref, new AbortController().signal, 'client');
557
552
  this.#releaseControllerIfTerminal(input.sessionId, input.ref, result);
558
- return {
559
- ok: true,
560
- result: decodeRuntimeResourceStopResult({
561
- resource: boundedRuntimeResourceSnapshot(runtimeResourceSnapshotFromResult(result)),
562
- }),
563
- };
553
+ return { ok: true, result: decodeRuntimeResourceStopResult({}) };
564
554
  }
565
555
  catch (error) {
566
556
  return this.#resourceFailure('runtime.resource.stop', error);
@@ -28,8 +28,11 @@ export function canonicalRuntimeResources(resources) {
28
28
  left.sourceToolCallId.localeCompare(right.sourceToolCallId));
29
29
  }
30
30
  function boundedRuntimeResourceUpdate(update) {
31
- const bounded = structuredClone(update);
32
- shrinkStateToFit(bounded.result);
31
+ return { ...update, result: boundedRuntimeResourceState(update.result) };
32
+ }
33
+ export function boundedRuntimeResourceState(state) {
34
+ const bounded = structuredClone(state);
35
+ shrinkStateToFit(bounded);
33
36
  return bounded;
34
37
  }
35
38
  export function runtimeResourceRevision(resources) {
@@ -68,20 +71,6 @@ export function createRuntimeResourcePage(sessionId, revision, resources, offset
68
71
  nextCursor: nextOffset < resources.length ? String(nextOffset) : null,
69
72
  });
70
73
  }
71
- export function boundedRuntimeResourceSnapshot(snapshot) {
72
- const bounded = structuredClone(snapshot);
73
- shrinkStateToFit(bounded);
74
- if (bounded.output === undefined)
75
- throw new Error('Runtime Resource snapshot lost its output');
76
- return bounded;
77
- }
78
- export function runtimeResourceSnapshotFromResult(result) {
79
- if (result.kind !== 'shell_run' || result.output === undefined) {
80
- throw new Error('Runtime Resource operation did not produce a ShellRun snapshot');
81
- }
82
- const { operation: _operation, ...snapshot } = result;
83
- return snapshot;
84
- }
85
74
  function shrinkStateToFit(state) {
86
75
  while (Buffer.byteLength(JSON.stringify(state), 'utf8') > RUNTIME_RESOURCE_SNAPSHOT_MAX_BYTES) {
87
76
  const fields = mutableTextFields(state).sort((left, right) => Buffer.byteLength(right.value(), 'utf8') - Buffer.byteLength(left.value(), 'utf8'));
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maka-agent",
3
- "version": "0.2.0-dev.40.20260917",
3
+ "version": "0.2.0-dev.42.20260918",
4
4
  "description": "Apache Maka (Incubating) developer snapshot; not an Apache release.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",