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
@@ -35,9 +35,56 @@ const MUTATE_ERRORS = [
35
35
  'operation_conflict',
36
36
  'commit_outcome_unknown',
37
37
  ];
38
+ const CLIENT_REMOTE_ERRORS = [
39
+ 'host_not_ready',
40
+ 'host_draining',
41
+ 'operation_unavailable',
42
+ 'invalid_request',
43
+ 'not_found',
44
+ 'operation_conflict',
45
+ 'internal_failure',
46
+ ];
38
47
  const MAX_FRAME_BYTES = 512 * 1024;
39
48
  export const PLUGIN_PLATFORM_QUERY_RESULT_MAX_BYTES = 480 * 1024;
49
+ export const PLUGIN_CLIENT_BUNDLE_CHUNK_MAX_BYTES = 192 * 1024;
50
+ export const PLUGIN_CLIENT_BUNDLE_MAX_BYTES = 8 * 1024 * 1024;
51
+ export const PLUGIN_CLIENT_REMOTE_VALUE_MAX_BYTES = 256 * 1024;
40
52
  export const PLUGIN_PLATFORM_OPERATION_SPECS = {
53
+ 'plugin.client.query': defineOperation({
54
+ mode: 'query',
55
+ availability: 'ready',
56
+ errors: [...QUERY_ERRORS, 'not_found'],
57
+ decodeInput: decodePluginClientQueryInput,
58
+ decodeOutput: decodePluginClientQueryResult,
59
+ }),
60
+ 'plugin.client.remote.call': defineOperation({
61
+ mode: 'control',
62
+ availability: 'ready',
63
+ errors: CLIENT_REMOTE_ERRORS,
64
+ decodeInput: decodePluginClientRemoteCallInput,
65
+ decodeOutput: decodePluginClientRemoteCallResult,
66
+ }),
67
+ 'plugin.client.remote.stream.open': defineOperation({
68
+ mode: 'control',
69
+ availability: 'ready',
70
+ errors: CLIENT_REMOTE_ERRORS,
71
+ decodeInput: decodePluginClientRemoteCallInput,
72
+ decodeOutput: decodePluginClientRemoteStreamOpenResult,
73
+ }),
74
+ 'plugin.client.remote.stream.next': defineOperation({
75
+ mode: 'control',
76
+ availability: 'ready',
77
+ errors: CLIENT_REMOTE_ERRORS,
78
+ decodeInput: decodePluginClientRemoteStreamCursorInput,
79
+ decodeOutput: decodePluginClientRemoteStreamNextResult,
80
+ }),
81
+ 'plugin.client.remote.stream.close': defineOperation({
82
+ mode: 'control',
83
+ availability: 'ready',
84
+ errors: CLIENT_REMOTE_ERRORS,
85
+ decodeInput: decodePluginClientRemoteStreamCursorInput,
86
+ decodeOutput: decodePluginClientRemoteStreamCloseResult,
87
+ }),
41
88
  'plugin.platform.query': defineOperation({
42
89
  mode: 'query',
43
90
  availability: 'ready',
@@ -106,6 +153,195 @@ export const PLUGIN_PLATFORM_OPERATION_SPECS = {
106
153
  decodeOutput: decodePluginMutationReceipt,
107
154
  }),
108
155
  };
156
+ function decodePluginClientRemoteCallInput(value) {
157
+ const input = requireShapedRecord(value, 'Plugin Client Remote call input', [
158
+ 'authorityEpoch',
159
+ 'revision',
160
+ 'entryId',
161
+ 'extensionId',
162
+ 'generation',
163
+ 'contentDigest',
164
+ 'clientDigest',
165
+ 'method',
166
+ 'input',
167
+ ], ['sessionId']);
168
+ const remoteInput = requireJsonValue(input.input, 'Plugin Client Remote input');
169
+ requireEncodedByteLimit(remoteInput, 'Plugin Client Remote input', PLUGIN_CLIENT_REMOTE_VALUE_MAX_BYTES);
170
+ const decoded = {
171
+ authorityEpoch: requireCount(input.authorityEpoch, 'Plugin authority epoch'),
172
+ revision: requireDigest(input.revision, 'Plugin Client composition revision'),
173
+ entryId: requireId(input.entryId, 'Plugin Client Entry identity'),
174
+ extensionId: requireId(input.extensionId, 'Plugin package identity'),
175
+ generation: requireCount(input.generation, 'Plugin Client generation'),
176
+ contentDigest: requireDigest(input.contentDigest, 'Plugin package content digest'),
177
+ clientDigest: requireDigest(input.clientDigest, 'Plugin Client bundle digest'),
178
+ method: requireRemoteMethod(input.method),
179
+ input: remoteInput,
180
+ ...(input.sessionId === undefined
181
+ ? {}
182
+ : { sessionId: requireId(input.sessionId, 'Plugin Client Remote Session identity') }),
183
+ };
184
+ requireEncodedByteLimit(decoded, 'Plugin Client Remote call input', MAX_FRAME_BYTES);
185
+ return decoded;
186
+ }
187
+ function decodePluginClientRemoteCallResult(value) {
188
+ const result = requireExactRecord(value, 'Plugin Client Remote call result', ['value']);
189
+ const decoded = { value: requireJsonValue(result.value, 'Plugin Client Remote result') };
190
+ requireEncodedByteLimit(decoded, 'Plugin Client Remote call result', PLUGIN_CLIENT_REMOTE_VALUE_MAX_BYTES);
191
+ return decoded;
192
+ }
193
+ function decodePluginClientRemoteStreamOpenResult(value) {
194
+ const result = requireExactRecord(value, 'Plugin Client Remote stream open result', ['streamId']);
195
+ return { streamId: requireId(result.streamId, 'Plugin Client Remote stream identity') };
196
+ }
197
+ function decodePluginClientRemoteStreamCursorInput(value) {
198
+ const input = requireExactRecord(value, 'Plugin Client Remote stream input', ['streamId']);
199
+ return { streamId: requireId(input.streamId, 'Plugin Client Remote stream identity') };
200
+ }
201
+ function decodePluginClientRemoteStreamNextResult(value) {
202
+ const result = requireRecord(value, 'Plugin Client Remote stream next result');
203
+ if (result.done === true) {
204
+ requireExactRecord(result, 'Plugin Client Remote completed stream result', ['done']);
205
+ return { done: true };
206
+ }
207
+ const item = requireExactRecord(result, 'Plugin Client Remote stream item result', [
208
+ 'done',
209
+ 'value',
210
+ ]);
211
+ if (item.done !== false)
212
+ throw invalidProtocolFrame('Invalid Plugin Client Remote stream state');
213
+ const decoded = {
214
+ done: false,
215
+ value: requireJsonValue(item.value, 'Plugin Client Remote stream item'),
216
+ };
217
+ requireEncodedByteLimit(decoded, 'Plugin Client Remote stream item', PLUGIN_CLIENT_REMOTE_VALUE_MAX_BYTES);
218
+ return decoded;
219
+ }
220
+ function decodePluginClientRemoteStreamCloseResult(value) {
221
+ const result = requireExactRecord(value, 'Plugin Client Remote stream close result', [
222
+ 'streamId',
223
+ ]);
224
+ return { streamId: requireId(result.streamId, 'Plugin Client Remote stream identity') };
225
+ }
226
+ function decodePluginClientQueryInput(value) {
227
+ const input = requireRecord(value, 'Plugin Client query input');
228
+ if (input.kind === 'snapshot') {
229
+ requireExactRecord(input, 'Plugin Client snapshot input', ['kind']);
230
+ return { kind: 'snapshot' };
231
+ }
232
+ if (input.kind === 'bundle') {
233
+ const bundle = requireExactRecord(input, 'Plugin Client bundle input', [
234
+ 'kind',
235
+ 'extensionId',
236
+ 'contentDigest',
237
+ 'clientDigest',
238
+ 'offset',
239
+ ]);
240
+ return {
241
+ kind: 'bundle',
242
+ extensionId: requireId(bundle.extensionId, 'Plugin package identity'),
243
+ contentDigest: requireDigest(bundle.contentDigest, 'Plugin package content digest'),
244
+ clientDigest: requireDigest(bundle.clientDigest, 'Plugin Client bundle digest'),
245
+ offset: requireCount(bundle.offset, 'Plugin Client bundle offset'),
246
+ };
247
+ }
248
+ throw invalidProtocolFrame('Invalid Plugin Client query kind');
249
+ }
250
+ function decodePluginClientQueryResult(value) {
251
+ const result = requireRecord(value, 'Plugin Client query result');
252
+ if (result.kind === 'snapshot') {
253
+ const snapshot = requireExactRecord(result, 'Plugin Client snapshot result', [
254
+ 'kind',
255
+ 'authorityEpoch',
256
+ 'revision',
257
+ 'entries',
258
+ 'failures',
259
+ ]);
260
+ if (!Array.isArray(snapshot.entries) || snapshot.entries.length > 1024) {
261
+ throw invalidProtocolFrame('Invalid Plugin Client composition entries');
262
+ }
263
+ if (!Array.isArray(snapshot.failures) || snapshot.failures.length > 1024) {
264
+ throw invalidProtocolFrame('Invalid Plugin Client failures');
265
+ }
266
+ const decoded = {
267
+ kind: 'snapshot',
268
+ authorityEpoch: requireCount(snapshot.authorityEpoch, 'Plugin authority epoch'),
269
+ revision: requireDigest(snapshot.revision, 'Plugin Client composition revision'),
270
+ entries: snapshot.entries.map(decodePluginClientCompositionEntry),
271
+ failures: snapshot.failures.map(decodePlatformFailure),
272
+ };
273
+ requireEncodedByteLimit(decoded, 'Plugin Client snapshot result', PLUGIN_PLATFORM_QUERY_RESULT_MAX_BYTES);
274
+ return decoded;
275
+ }
276
+ if (result.kind === 'bundle') {
277
+ const bundle = requireExactRecord(result, 'Plugin Client bundle result', [
278
+ 'kind',
279
+ 'extensionId',
280
+ 'contentDigest',
281
+ 'clientDigest',
282
+ 'offset',
283
+ 'totalBytes',
284
+ 'content',
285
+ 'nextOffset',
286
+ ]);
287
+ const offset = requireCount(bundle.offset, 'Plugin Client bundle offset');
288
+ const totalBytes = requireCount(bundle.totalBytes, 'Plugin Client bundle size');
289
+ const content = requireString(bundle.content, 'Plugin Client bundle content', Math.ceil((PLUGIN_CLIENT_BUNDLE_CHUNK_MAX_BYTES * 4) / 3) + 4);
290
+ const decodedBytes = Buffer.from(content, 'base64');
291
+ if (decodedBytes.byteLength === 0 ||
292
+ decodedBytes.byteLength > PLUGIN_CLIENT_BUNDLE_CHUNK_MAX_BYTES ||
293
+ decodedBytes.toString('base64') !== content) {
294
+ throw invalidProtocolFrame('Invalid Plugin Client bundle content');
295
+ }
296
+ const nextOffset = bundle.nextOffset === null
297
+ ? null
298
+ : requireCount(bundle.nextOffset, 'Plugin Client next bundle offset');
299
+ if (offset >= totalBytes ||
300
+ offset + decodedBytes.byteLength > totalBytes ||
301
+ (nextOffset === null
302
+ ? offset + decodedBytes.byteLength !== totalBytes
303
+ : nextOffset !== offset + decodedBytes.byteLength || nextOffset >= totalBytes)) {
304
+ throw invalidProtocolFrame('Invalid Plugin Client bundle range');
305
+ }
306
+ return {
307
+ kind: 'bundle',
308
+ extensionId: requireId(bundle.extensionId, 'Plugin package identity'),
309
+ contentDigest: requireDigest(bundle.contentDigest, 'Plugin package content digest'),
310
+ clientDigest: requireDigest(bundle.clientDigest, 'Plugin Client bundle digest'),
311
+ offset,
312
+ totalBytes,
313
+ content,
314
+ nextOffset,
315
+ };
316
+ }
317
+ throw invalidProtocolFrame('Invalid Plugin Client query result kind');
318
+ }
319
+ function decodePluginClientCompositionEntry(value) {
320
+ const entry = requireShapedRecord(value, 'Plugin Client composition entry', [
321
+ 'entryId',
322
+ 'extensionId',
323
+ 'generation',
324
+ 'contentDigest',
325
+ 'clientDigest',
326
+ 'totalBytes',
327
+ 'dependencies',
328
+ ], ['config']);
329
+ if (!Array.isArray(entry.dependencies) || entry.dependencies.length > 64) {
330
+ throw invalidProtocolFrame('Invalid Plugin Client dependencies');
331
+ }
332
+ return {
333
+ entryId: requireId(entry.entryId, 'Plugin Client Entry identity'),
334
+ extensionId: requireId(entry.extensionId, 'Plugin package identity'),
335
+ generation: requireCount(entry.generation, 'Plugin Client generation'),
336
+ contentDigest: requireDigest(entry.contentDigest, 'Plugin package content digest'),
337
+ clientDigest: requireDigest(entry.clientDigest, 'Plugin Client bundle digest'),
338
+ totalBytes: requireCount(entry.totalBytes, 'Plugin Client bundle size'),
339
+ dependencies: entry.dependencies.map((dependency) => requireId(dependency, 'Plugin Client dependency identity')),
340
+ ...(entry.config === undefined
341
+ ? {}
342
+ : { config: decodeScalarRecord(entry.config, 'Client config') }),
343
+ };
344
+ }
109
345
  function decodePluginPlatformQueryInput(value) {
110
346
  const input = requireShapedRecord(value, 'Plugin Platform query input', ['view'], ['rootId', 'cursor', 'limit']);
111
347
  if (!['status', 'packages', 'entries', 'tools', 'commands', 'executors', 'failures'].includes(input.view)) {
@@ -583,6 +819,39 @@ function decodeScalarRecord(value, label) {
583
819
  }
584
820
  return Object.fromEntries(output);
585
821
  }
822
+ function requireRemoteMethod(value) {
823
+ const method = requireString(value, 'Plugin Client Remote method', 128);
824
+ if (!/^[a-z][a-z0-9]*(?:[._:/-][a-z0-9]+)*$/u.test(method)) {
825
+ throw invalidProtocolFrame('Invalid Plugin Client Remote method');
826
+ }
827
+ return method;
828
+ }
829
+ function requireJsonValue(value, label, depth = 0) {
830
+ if (depth > 32)
831
+ throw invalidProtocolFrame(`${label} is too deeply nested`);
832
+ if (value === null ||
833
+ typeof value === 'string' ||
834
+ typeof value === 'boolean' ||
835
+ (typeof value === 'number' && Number.isFinite(value))) {
836
+ return value;
837
+ }
838
+ if (Array.isArray(value)) {
839
+ if (value.length > 16_384)
840
+ throw invalidProtocolFrame(`${label} has too many items`);
841
+ return value.map((item) => requireJsonValue(item, label, depth + 1));
842
+ }
843
+ if (!value || typeof value !== 'object')
844
+ throw invalidProtocolFrame(`Invalid ${label}`);
845
+ const prototype = Object.getPrototypeOf(value);
846
+ if (prototype !== Object.prototype && prototype !== null) {
847
+ throw invalidProtocolFrame(`Invalid ${label}`);
848
+ }
849
+ const record = value;
850
+ if (Object.keys(record).length > 16_384) {
851
+ throw invalidProtocolFrame(`${label} has too many fields`);
852
+ }
853
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [key, requireJsonValue(item, label, depth + 1)]));
854
+ }
586
855
  function requireBoolean(value) {
587
856
  if (typeof value !== 'boolean')
588
857
  throw invalidProtocolFrame('Invalid Plugin Entry disabled flag');
@@ -48,11 +48,13 @@ export const WORKHUB_COORDINATION_TEXT_MAX_BYTES = 48 * 1024;
48
48
  const COORDINATION_TITLE_MAX_BYTES = 512;
49
49
  const CANDIDATE_SET_ID_MAX_BYTES = 96;
50
50
  export const WORKHUB_COORDINATION_CANDIDATE_MAX_ITEMS = 32;
51
+ export const WORKHUB_COORDINATION_DEFAULT_MODEL_REQUIRED_MESSAGE = 'WorkHub Coordination Session requires an available default model';
51
52
  const RESOLVE_ERRORS = [
52
53
  'host_not_ready',
53
54
  'host_draining',
54
55
  'operation_unavailable',
55
56
  'operation_conflict',
57
+ 'model_required',
56
58
  'persistence_failed',
57
59
  'commit_outcome_unknown',
58
60
  'internal_failure',
@@ -32,6 +32,7 @@ import { BackendRegistry, SessionManager, workHubDirectStopAbortSource, } from '
32
32
  import { buildToolsForAgentDefinition } from '@maka/runtime/agent-catalog';
33
33
  import { buildRecallTools } from '@maka/runtime/recall-tools';
34
34
  import { RECALL_SYNTHETIC_TEXT_PATTERNS } from '@maka/runtime/recall-candidates';
35
+ import { createRecallMaterialFetch } from './recall-material-fetch.js';
35
36
  import { buildBuiltinTools } from '@maka/runtime/builtin-tools';
36
37
  import { createLocalContinuationSafetyInspector } from '@maka/runtime/continuation-safety';
37
38
  import { createConfiguredSubagentCatalog } from '@maka/runtime/configured-subagent-catalog';
@@ -61,6 +62,7 @@ import { MakaCompositionLoader } from '@maka/runtime/plugin-composition-loader';
61
62
  import { PluginToolService } from '@maka/runtime/plugin-tool-service';
62
63
  import { PluginSystemPromptService } from '@maka/runtime/plugin-system-prompt-service';
63
64
  import { PluginCommandService } from '@maka/runtime/plugin-command-service';
65
+ import { PluginClientBridgeService } from '@maka/runtime/plugin-client-bridge-service';
64
66
  import { PluginAuthorizationService, PluginCredentialService, PluginSettingsService, PluginStorageService, } from '@maka/runtime/plugin-data-services';
65
67
  import { PluginGoalService } from '@maka/runtime/plugin-goal-service';
66
68
  import { PluginLspService } from '@maka/runtime/plugin-lsp-service';
@@ -107,6 +109,7 @@ import { HostHostedExecutionRunner } from './hosted-execution-runner.js';
107
109
  import { executeHostedExecutionToSettlement, waitForHostedExecutionIdleOrAbort, } from './hosted-execution-wait.js';
108
110
  import { beginRuntimeHostDomainModuleDrain, closeRuntimeHostDomainModules, composeRuntimeHostDomainHandlers, createRuntimeHostDomainModule, recoverRuntimeHostDomainModules, } from './host-composition.js';
109
111
  import { HostInteractionCoordinator } from './interaction-coordinator.js';
112
+ import { HostWorkHubTargetExecutionAuthority } from './workhub-target-execution-authority.js';
110
113
  import { HostInteractiveTurnCoordinator } from './interactive-turn-coordinator.js';
111
114
  import { SessionTurnAccessRequestCoordinator } from './session-turn-access-request-coordinator.js';
112
115
  import { ensureBootstrapRuntimePolicy } from './bootstrap-runtime-policy.js';
@@ -228,6 +231,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
228
231
  const pluginGoals = new PluginGoalService(pluginRoot, pluginAgents);
229
232
  const pluginSkills = new PluginSkillService(pluginRoot);
230
233
  const pluginCommands = new PluginCommandService(pluginRoot);
234
+ const pluginClientBridge = new PluginClientBridgeService(pluginRoot);
231
235
  new PluginLspService(pluginRoot);
232
236
  const pluginSettings = new PluginSettingsService(pluginRoot);
233
237
  const pluginStorage = new PluginStorageService(pluginRoot);
@@ -245,6 +249,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
245
249
  systemPrompt: pluginSystemPrompt,
246
250
  commands: pluginCommands,
247
251
  executors: pluginExecutors,
252
+ clientBridge: pluginClientBridge,
248
253
  });
249
254
  const pluginPlatformCoordinator = new HostPluginPlatformCoordinator(pluginPlatform);
250
255
  const openedProjectCatalog = storage.projectCatalog;
@@ -364,12 +369,15 @@ export async function createExecutionRuntimeHostComposition(context, options = {
364
369
  sessionAdmission,
365
370
  sessions: stores.sessionStore,
366
371
  });
372
+ // Shared with recall's material fetch, so a file brought in from another
373
+ // Session is answered by the same reader that answers one stored here.
374
+ const attachmentResources = createArtifactAttachmentResourceReader({
375
+ artifactStore: openedArtifactStore,
376
+ });
367
377
  const builtinTools = {
368
378
  shellRuns: runtimeResources,
369
379
  runtimeResources,
370
- attachmentResources: createArtifactAttachmentResourceReader({
371
- artifactStore: openedArtifactStore,
372
- }),
380
+ attachmentResources,
373
381
  backgroundTasks: runtimeResources,
374
382
  ptyControls: runtimeResources,
375
383
  ...(openedContextOffloadStore
@@ -504,6 +512,10 @@ export async function createExecutionRuntimeHostComposition(context, options = {
504
512
  .countRecallSearchableMessages(sessionIds)
505
513
  .catch(() => undefined)) ?? null,
506
514
  syntheticTextPatterns: RECALL_SYNTHETIC_TEXT_PATTERNS,
515
+ fetchMaterial: createRecallMaterialFetch({
516
+ artifacts: openedArtifactStore,
517
+ attachments: attachmentResources,
518
+ }),
507
519
  searchFacts: async ({ sessionId, terms, limit }) => {
508
520
  const workspaceKey = sessionId
509
521
  ? await stores.sessionStore
@@ -1621,9 +1633,29 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1621
1633
  ? { sessionAccessAuthority: context.sessionAccessAuthority }
1622
1634
  : {}),
1623
1635
  });
1636
+ const workHubTargetExecution = new HostWorkHubTargetExecutionAuthority({
1637
+ readSession: (sessionId) => stores.sessionStore.readHeaderRecordSnapshot(sessionId),
1638
+ runtimePolicy: {
1639
+ resolveExecutionConnection: (locator) => runtimePolicyStores.operations.resolveExecutionConnection(locator),
1640
+ connectionCatalog: runtimePolicyStores.connectionCatalog,
1641
+ },
1642
+ requestForm: (input) => interactions.requestForm(input),
1643
+ updateModel: async (input, operationContext) => {
1644
+ const outcome = await sessionCatalog.handlers['session.configuration.update']({
1645
+ sessionId: input.sessionId,
1646
+ expectedRevision: input.expectedRevision,
1647
+ patch: { modelTarget: input.modelTarget },
1648
+ }, operationContext);
1649
+ if (!outcome.ok) {
1650
+ throw new WorkHubActionEffectFailure(outcome.error.code === 'invalid_request' ? 'operation_conflict' : outcome.error.code, outcome.error.message);
1651
+ }
1652
+ return outcome.result.kind === 'committed' ? 'committed' : 'revision_conflict';
1653
+ },
1654
+ });
1624
1655
  workHubCoordination = new HostWorkHubCoordinationCoordinator({
1625
1656
  routingModel: dependencies.workHubRoutingModel,
1626
1657
  requestForm: (input) => interactions.requestForm(input),
1658
+ targetExecution: workHubTargetExecution,
1627
1659
  configureModel: (input) => sessionCatalog.configureWorkHubModel(input),
1628
1660
  transitionConfiguration: (input) => requireSessionManager(manager).transitionSessionConfiguration(WORKHUB_COORDINATION_SESSION_ID, input),
1629
1661
  stateRoot: context.owner.capability.canonicalPath,
@@ -1659,7 +1691,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1659
1691
  // Resolve and resume only the execution lineage owned by this
1660
1692
  // delegation. A Session-wide latest-failure query could otherwise
1661
1693
  // continue unrelated work started directly in the same Session.
1662
- resumeDelegation: async (assignment, context, actionId, validateFreshTarget) => {
1694
+ resumeDelegation: async (assignment, context, actionId, validateFreshTarget, prepareTargetExecution, assertTargetExecutionReady) => {
1663
1695
  const targetTurnId = workHubResumedTurnId(actionId);
1664
1696
  const admitted = await stores.agentRunStore.readRootTurnAdmission(assignment.targetSessionId, targetTurnId);
1665
1697
  if (admitted) {
@@ -1669,6 +1701,11 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1669
1701
  return { outcome: 'resume_started', targetTurnId };
1670
1702
  }
1671
1703
  await validateFreshTarget();
1704
+ await prepareTargetExecution?.();
1705
+ // A model-repair form can remain open while another action changes
1706
+ // the delegated target. Recheck freshness before reading its
1707
+ // terminal lineage so the resumed action never uses a stale target.
1708
+ await validateFreshTarget();
1672
1709
  const disposition = await messages.readMessageExecutionDisposition(assignment.targetSessionId, assignment.targetMessageId);
1673
1710
  if (disposition.kind === 'recovering') {
1674
1711
  throw new WorkHubActionEffectFailure('host_not_ready', 'WorkHub is still recovering the delegated execution');
@@ -1706,12 +1743,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1706
1743
  if (plan.result.sourceTurnId !== source.turnId) {
1707
1744
  throw new WorkHubActionEffectFailure('operation_conflict', 'WorkHub resume source lineage changed during planning');
1708
1745
  }
1709
- const started = await coordinator.handlers['turn.resume.start']({
1746
+ const started = await coordinator.startTurnResumeWithValidation({
1710
1747
  sessionId: assignment.targetSessionId,
1711
1748
  turnId: targetTurnId,
1712
1749
  sourceRunId: plan.result.sourceRunId,
1713
1750
  sourceRuntimeEventHighWater: plan.result.sourceRuntimeEventHighWater,
1714
- }, context);
1751
+ }, context, assertTargetExecutionReady);
1715
1752
  if (!started.ok) {
1716
1753
  throw new WorkHubActionEffectFailure(started.error.code, started.error.message);
1717
1754
  }
@@ -2054,6 +2091,9 @@ export async function createExecutionRuntimeHostComposition(context, options = {
2054
2091
  recovery: { state: () => pluginPlatform.recover() },
2055
2092
  drain: [() => pluginPlatform.beginDrain()],
2056
2093
  close: [() => pluginPlatform.close()],
2094
+ releaseConnection: [
2095
+ (connectionId) => pluginPlatformCoordinator.releaseConnection(connectionId),
2096
+ ],
2057
2097
  }),
2058
2098
  createRuntimeHostDomainModule({
2059
2099
  id: 'memory',
@@ -52,7 +52,15 @@ export async function loadExtensionPackageManifest(root) {
52
52
  }
53
53
  export function decodeExtensionPackageManifest(value) {
54
54
  const source = record(value, 'Extension manifest');
55
- exactOptional(source, ['schemaVersion', 'id'], ['displayName', 'description', 'dependencies', 'configuration', 'runtime', 'composition']);
55
+ exactOptional(source, ['schemaVersion', 'id'], [
56
+ 'displayName',
57
+ 'description',
58
+ 'dependencies',
59
+ 'configuration',
60
+ 'runtime',
61
+ 'client',
62
+ 'composition',
63
+ ]);
56
64
  if (source.schemaVersion !== 1)
57
65
  throw invalid('Extension manifest schemaVersion must be 1');
58
66
  const id = extensionId(source.id);
@@ -61,6 +69,7 @@ export function decodeExtensionPackageManifest(value) {
61
69
  const dependencies = decodeDependencies(source.dependencies);
62
70
  const configuration = decodeConfigurationSchema(source.configuration);
63
71
  const runtime = decodeRuntime(source.runtime);
72
+ const client = decodeClient(source.client);
64
73
  const composition = decodeComposition(source.composition);
65
74
  return Object.freeze({
66
75
  schemaVersion: 1,
@@ -70,6 +79,7 @@ export function decodeExtensionPackageManifest(value) {
70
79
  dependencies,
71
80
  configuration,
72
81
  ...(runtime === undefined ? {} : { runtime }),
82
+ ...(client === undefined ? {} : { client }),
73
83
  ...(composition === undefined ? {} : { composition }),
74
84
  });
75
85
  }
@@ -88,10 +98,18 @@ function decodeRuntime(value) {
88
98
  if (value === undefined)
89
99
  return undefined;
90
100
  const runtime = record(value, 'runtime');
101
+ exactOptional(runtime, ['entry'], []);
91
102
  if (runtime.entry === undefined)
92
103
  return undefined;
93
104
  return Object.freeze({ entry: packagePath(runtime.entry, 'runtime.entry') });
94
105
  }
106
+ function decodeClient(value) {
107
+ if (value === undefined)
108
+ return undefined;
109
+ const client = record(value, 'client');
110
+ exactOptional(client, ['entry'], []);
111
+ return Object.freeze({ entry: packagePath(client.entry, 'client.entry') });
112
+ }
95
113
  function packagePath(value, label) {
96
114
  if (typeof value !== 'string' ||
97
115
  value.length === 0 ||
@@ -16,14 +16,19 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { randomUUID } from 'node:crypto';
20
- import { cp, mkdir, rm } from 'node:fs/promises';
19
+ import { createHash, randomUUID } from 'node:crypto';
20
+ import { cp, mkdir, open, readFile, readdir, rm } from 'node:fs/promises';
21
21
  import { join, relative } from 'node:path';
22
22
  import { pathToFileURL } from 'node:url';
23
23
  import { MakaPluginRuntimeError, validatePluginPackage, } from '@maka/runtime/plugin-runtime';
24
24
  import { PluginPackageStoreError, } from './plugin-package-store.js';
25
25
  const GENERATION_DIRECTORY = 'plugin-generations-v1';
26
26
  const GENERATION_PATH = Symbol('maka.pluginGenerationPath');
27
+ const CLIENT_BUNDLE = Symbol('maka.clientPluginBundle');
28
+ const clientMarker = Object.freeze({
29
+ name: 'maka-client-composition-marker',
30
+ apply() { },
31
+ });
27
32
  export class PluginPackageLoaderError extends Error {
28
33
  code;
29
34
  name = 'PluginPackageLoaderError';
@@ -61,20 +66,42 @@ export class TrustedPluginPackageLoader {
61
66
  errorOnExist: true,
62
67
  preserveTimestamps: false,
63
68
  });
64
- const entry = join(generation, relative(installed.root, installed.entry));
65
- const imported = (await import(pathToFileURL(entry).href));
66
- const candidate = imported.default ?? imported.plugin;
67
- if (!candidate || typeof candidate !== 'object') {
68
- throw invalid('Plugin Runtime entry must export a MakaPluginPackage as default');
69
+ let pkg;
70
+ if (installed.entry) {
71
+ const entry = join(generation, relative(installed.root, installed.entry));
72
+ const imported = (await import(pathToFileURL(entry).href));
73
+ const candidate = imported.default ?? imported.plugin;
74
+ if (!candidate || typeof candidate !== 'object') {
75
+ throw invalid('Plugin Runtime entry must export a MakaPluginPackage as default');
76
+ }
77
+ pkg = candidate;
69
78
  }
70
- const pkg = candidate;
79
+ else {
80
+ pkg = { packageId: installed.extensionId, client: clientMarker };
81
+ }
82
+ if (installed.clientEntry)
83
+ pkg = { ...pkg, client: clientMarker };
71
84
  validatePluginPackage(pkg);
72
85
  if (pkg.packageId !== installed.extensionId) {
73
86
  throw invalid(`Plugin Runtime packageId ${pkg.packageId} does not match manifest ${installed.extensionId}`);
74
87
  }
75
- if (!pkg.host)
76
- throw invalid('Trusted Host package must export a host Plugin');
77
- const owned = freezeGeneration(pkg, generation);
88
+ if (installed.entry && !pkg.host) {
89
+ throw invalid('Trusted Runtime entry must export a host Plugin');
90
+ }
91
+ let clientBundle;
92
+ if (installed.clientEntry) {
93
+ const path = join(generation, relative(installed.root, installed.clientEntry));
94
+ const content = await readFile(path);
95
+ clientBundle = Object.freeze({
96
+ extensionId: installed.extensionId,
97
+ contentDigest: installed.contentDigest,
98
+ clientDigest: `sha256-${createHash('sha256').update(content).digest('hex')}`,
99
+ totalBytes: content.byteLength,
100
+ path,
101
+ generation,
102
+ });
103
+ }
104
+ const owned = freezeGeneration(pkg, generation, clientBundle);
78
105
  this.#owned.add(generation);
79
106
  return owned;
80
107
  }
@@ -84,8 +111,16 @@ export class TrustedPluginPackageLoader {
84
111
  }
85
112
  }
86
113
  async collectGarbage() {
87
- this.#owned.clear();
88
- await rm(this.#generations, { recursive: true, force: true });
114
+ const entries = await readdir(this.#generations).catch((error) => {
115
+ if (error.code === 'ENOENT')
116
+ return [];
117
+ throw error;
118
+ });
119
+ for (const name of entries) {
120
+ const path = join(this.#generations, name);
121
+ if (!this.#owned.has(path))
122
+ await rm(path, { recursive: true, force: true });
123
+ }
89
124
  }
90
125
  async release(pkg) {
91
126
  const generation = pkg[GENERATION_PATH];
@@ -93,15 +128,51 @@ export class TrustedPluginPackageLoader {
93
128
  return;
94
129
  await rm(generation, { recursive: true, force: true });
95
130
  }
131
+ clientBundle(pkg) {
132
+ const bundle = clientBundleOf(pkg);
133
+ if (!bundle || !this.#owned.has(bundle.generation))
134
+ return undefined;
135
+ return Object.freeze({
136
+ extensionId: bundle.extensionId,
137
+ contentDigest: bundle.contentDigest,
138
+ clientDigest: bundle.clientDigest,
139
+ totalBytes: bundle.totalBytes,
140
+ });
141
+ }
142
+ async readClientBundle(pkg, offset, maxBytes) {
143
+ const bundle = clientBundleOf(pkg);
144
+ if (!bundle || !this.#owned.has(bundle.generation)) {
145
+ throw new PluginPackageLoaderError('not_found', `Plugin package has no active Client generation: ${pkg.packageId}`);
146
+ }
147
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= bundle.totalBytes) {
148
+ throw invalid('Plugin Client bundle offset is invalid');
149
+ }
150
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
151
+ throw invalid('Plugin Client bundle read size is invalid');
152
+ }
153
+ const handle = await open(bundle.path, 'r');
154
+ try {
155
+ const length = Math.min(maxBytes, bundle.totalBytes - offset);
156
+ const content = Buffer.allocUnsafe(length);
157
+ const { bytesRead } = await handle.read(content, 0, length, offset);
158
+ if (bytesRead !== length)
159
+ throw invalid('Plugin Client bundle ended unexpectedly');
160
+ return Object.freeze({ content, totalBytes: bundle.totalBytes });
161
+ }
162
+ finally {
163
+ await handle.close();
164
+ }
165
+ }
96
166
  async close() {
97
167
  this.#owned.clear();
98
168
  await rm(this.#generations, { recursive: true, force: true });
99
169
  }
100
170
  }
101
- function freezeGeneration(pkg, generation) {
171
+ function freezeGeneration(pkg, generation, clientBundle) {
102
172
  return Object.freeze({
103
173
  ...pkg,
104
174
  [GENERATION_PATH]: generation,
175
+ ...(clientBundle ? { [CLIENT_BUNDLE]: clientBundle } : {}),
105
176
  ...(pkg.contributions
106
177
  ? {
107
178
  contributions: Object.freeze(pkg.contributions.map((item) => Object.freeze({ ...item }))),
@@ -109,6 +180,9 @@ function freezeGeneration(pkg, generation) {
109
180
  : {}),
110
181
  });
111
182
  }
183
+ function clientBundleOf(pkg) {
184
+ return pkg[CLIENT_BUNDLE];
185
+ }
112
186
  function invalid(message, cause) {
113
187
  return new PluginPackageLoaderError('invalid_package', message, { cause });
114
188
  }