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
@@ -24,6 +24,7 @@ import { NO_REAL_CONNECTION_CODE } from '@maka/core/connection-error-copy';
24
24
  import { generalizedErrorMessage } from '@maka/core/redaction';
25
25
  import { emptyPlanSessionState } from '@maka/core/plan';
26
26
  import { readLogicalRuntimeExecutionForRun } from '@maka/core/runtime-logical-execution';
27
+ import { foldForMatch } from '@maka/core/thread-search';
27
28
  import { runtimeInvocationOutcome, } from '@maka/core/runtime-invocation';
28
29
  import { isDeepResearchSession, WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_REPLACEMENT_SCHEMA_VERSION, } from '@maka/core/session';
29
30
  import { AgentGraphClientOperationError, AgentGraphCoordinator, } from '@maka/runtime/stream-graph-coordinator';
@@ -32,6 +33,7 @@ import { BackendRegistry, SessionManager, workHubDirectStopAbortSource, } from '
32
33
  import { buildToolsForAgentDefinition } from '@maka/runtime/agent-catalog';
33
34
  import { buildRecallTools } from '@maka/runtime/recall-tools';
34
35
  import { RECALL_SYNTHETIC_TEXT_PATTERNS } from '@maka/runtime/recall-candidates';
36
+ import { createRecallMaterialFetch } from './recall-material-fetch.js';
35
37
  import { buildBuiltinTools } from '@maka/runtime/builtin-tools';
36
38
  import { createLocalContinuationSafetyInspector } from '@maka/runtime/continuation-safety';
37
39
  import { createConfiguredSubagentCatalog } from '@maka/runtime/configured-subagent-catalog';
@@ -61,6 +63,7 @@ import { MakaCompositionLoader } from '@maka/runtime/plugin-composition-loader';
61
63
  import { PluginToolService } from '@maka/runtime/plugin-tool-service';
62
64
  import { PluginSystemPromptService } from '@maka/runtime/plugin-system-prompt-service';
63
65
  import { PluginCommandService } from '@maka/runtime/plugin-command-service';
66
+ import { PluginClientBridgeService } from '@maka/runtime/plugin-client-bridge-service';
64
67
  import { PluginAuthorizationService, PluginCredentialService, PluginSettingsService, PluginStorageService, } from '@maka/runtime/plugin-data-services';
65
68
  import { PluginGoalService } from '@maka/runtime/plugin-goal-service';
66
69
  import { PluginLspService } from '@maka/runtime/plugin-lsp-service';
@@ -107,6 +110,7 @@ import { HostHostedExecutionRunner } from './hosted-execution-runner.js';
107
110
  import { executeHostedExecutionToSettlement, waitForHostedExecutionIdleOrAbort, } from './hosted-execution-wait.js';
108
111
  import { beginRuntimeHostDomainModuleDrain, closeRuntimeHostDomainModules, composeRuntimeHostDomainHandlers, createRuntimeHostDomainModule, recoverRuntimeHostDomainModules, } from './host-composition.js';
109
112
  import { HostInteractionCoordinator } from './interaction-coordinator.js';
113
+ import { HostWorkHubTargetExecutionAuthority } from './workhub-target-execution-authority.js';
110
114
  import { HostInteractiveTurnCoordinator } from './interactive-turn-coordinator.js';
111
115
  import { SessionTurnAccessRequestCoordinator } from './session-turn-access-request-coordinator.js';
112
116
  import { ensureBootstrapRuntimePolicy } from './bootstrap-runtime-policy.js';
@@ -228,6 +232,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
228
232
  const pluginGoals = new PluginGoalService(pluginRoot, pluginAgents);
229
233
  const pluginSkills = new PluginSkillService(pluginRoot);
230
234
  const pluginCommands = new PluginCommandService(pluginRoot);
235
+ const pluginClientBridge = new PluginClientBridgeService(pluginRoot);
231
236
  new PluginLspService(pluginRoot);
232
237
  const pluginSettings = new PluginSettingsService(pluginRoot);
233
238
  const pluginStorage = new PluginStorageService(pluginRoot);
@@ -245,6 +250,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
245
250
  systemPrompt: pluginSystemPrompt,
246
251
  commands: pluginCommands,
247
252
  executors: pluginExecutors,
253
+ clientBridge: pluginClientBridge,
248
254
  });
249
255
  const pluginPlatformCoordinator = new HostPluginPlatformCoordinator(pluginPlatform);
250
256
  const openedProjectCatalog = storage.projectCatalog;
@@ -364,12 +370,15 @@ export async function createExecutionRuntimeHostComposition(context, options = {
364
370
  sessionAdmission,
365
371
  sessions: stores.sessionStore,
366
372
  });
373
+ // Shared with recall's material fetch, so a file brought in from another
374
+ // Session is answered by the same reader that answers one stored here.
375
+ const attachmentResources = createArtifactAttachmentResourceReader({
376
+ artifactStore: openedArtifactStore,
377
+ });
367
378
  const builtinTools = {
368
379
  shellRuns: runtimeResources,
369
380
  runtimeResources,
370
- attachmentResources: createArtifactAttachmentResourceReader({
371
- artifactStore: openedArtifactStore,
372
- }),
381
+ attachmentResources,
373
382
  backgroundTasks: runtimeResources,
374
383
  ptyControls: runtimeResources,
375
384
  ...(openedContextOffloadStore
@@ -504,6 +513,10 @@ export async function createExecutionRuntimeHostComposition(context, options = {
504
513
  .countRecallSearchableMessages(sessionIds)
505
514
  .catch(() => undefined)) ?? null,
506
515
  syntheticTextPatterns: RECALL_SYNTHETIC_TEXT_PATTERNS,
516
+ fetchMaterial: createRecallMaterialFetch({
517
+ artifacts: openedArtifactStore,
518
+ attachments: attachmentResources,
519
+ }),
507
520
  searchFacts: async ({ sessionId, terms, limit }) => {
508
521
  const workspaceKey = sessionId
509
522
  ? await stores.sessionStore
@@ -1299,17 +1312,17 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1299
1312
  });
1300
1313
  },
1301
1314
  search: async (request, caller) => {
1302
- const query = request.query.toLocaleLowerCase();
1315
+ const query = foldForMatch(request.query);
1303
1316
  const sessions = await visibleAgentSessions(sessionQueryInitiator(caller));
1304
1317
  const matches = [];
1305
1318
  for (const session of sessions) {
1306
- const headerText = `${session.name}\n${session.cwd ?? ''}`.toLocaleLowerCase();
1319
+ const headerText = foldForMatch(`${session.name}\n${session.cwd ?? ''}`);
1307
1320
  if (headerText.includes(query)) {
1308
1321
  matches.push(session);
1309
1322
  continue;
1310
1323
  }
1311
1324
  const messages = await requireSessionManager(manager).getMessages(session.id);
1312
- if (messages.some((message) => JSON.stringify(message).toLocaleLowerCase().includes(query))) {
1325
+ if (messages.some((message) => foldForMatch(JSON.stringify(message)).includes(query))) {
1313
1326
  matches.push(session);
1314
1327
  }
1315
1328
  }
@@ -1621,9 +1634,29 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1621
1634
  ? { sessionAccessAuthority: context.sessionAccessAuthority }
1622
1635
  : {}),
1623
1636
  });
1637
+ const workHubTargetExecution = new HostWorkHubTargetExecutionAuthority({
1638
+ readSession: (sessionId) => stores.sessionStore.readHeaderRecordSnapshot(sessionId),
1639
+ runtimePolicy: {
1640
+ resolveExecutionConnection: (locator) => runtimePolicyStores.operations.resolveExecutionConnection(locator),
1641
+ connectionCatalog: runtimePolicyStores.connectionCatalog,
1642
+ },
1643
+ requestForm: (input) => interactions.requestForm(input),
1644
+ updateModel: async (input, operationContext) => {
1645
+ const outcome = await sessionCatalog.handlers['session.configuration.update']({
1646
+ sessionId: input.sessionId,
1647
+ expectedRevision: input.expectedRevision,
1648
+ patch: { modelTarget: input.modelTarget },
1649
+ }, operationContext);
1650
+ if (!outcome.ok) {
1651
+ throw new WorkHubActionEffectFailure(outcome.error.code === 'invalid_request' ? 'operation_conflict' : outcome.error.code, outcome.error.message);
1652
+ }
1653
+ return outcome.result.kind === 'committed' ? 'committed' : 'revision_conflict';
1654
+ },
1655
+ });
1624
1656
  workHubCoordination = new HostWorkHubCoordinationCoordinator({
1625
1657
  routingModel: dependencies.workHubRoutingModel,
1626
1658
  requestForm: (input) => interactions.requestForm(input),
1659
+ targetExecution: workHubTargetExecution,
1627
1660
  configureModel: (input) => sessionCatalog.configureWorkHubModel(input),
1628
1661
  transitionConfiguration: (input) => requireSessionManager(manager).transitionSessionConfiguration(WORKHUB_COORDINATION_SESSION_ID, input),
1629
1662
  stateRoot: context.owner.capability.canonicalPath,
@@ -1659,7 +1692,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1659
1692
  // Resolve and resume only the execution lineage owned by this
1660
1693
  // delegation. A Session-wide latest-failure query could otherwise
1661
1694
  // continue unrelated work started directly in the same Session.
1662
- resumeDelegation: async (assignment, context, actionId, validateFreshTarget) => {
1695
+ resumeDelegation: async (assignment, context, actionId, validateFreshTarget, prepareTargetExecution, assertTargetExecutionReady) => {
1663
1696
  const targetTurnId = workHubResumedTurnId(actionId);
1664
1697
  const admitted = await stores.agentRunStore.readRootTurnAdmission(assignment.targetSessionId, targetTurnId);
1665
1698
  if (admitted) {
@@ -1669,6 +1702,11 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1669
1702
  return { outcome: 'resume_started', targetTurnId };
1670
1703
  }
1671
1704
  await validateFreshTarget();
1705
+ await prepareTargetExecution?.();
1706
+ // A model-repair form can remain open while another action changes
1707
+ // the delegated target. Recheck freshness before reading its
1708
+ // terminal lineage so the resumed action never uses a stale target.
1709
+ await validateFreshTarget();
1672
1710
  const disposition = await messages.readMessageExecutionDisposition(assignment.targetSessionId, assignment.targetMessageId);
1673
1711
  if (disposition.kind === 'recovering') {
1674
1712
  throw new WorkHubActionEffectFailure('host_not_ready', 'WorkHub is still recovering the delegated execution');
@@ -1706,12 +1744,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1706
1744
  if (plan.result.sourceTurnId !== source.turnId) {
1707
1745
  throw new WorkHubActionEffectFailure('operation_conflict', 'WorkHub resume source lineage changed during planning');
1708
1746
  }
1709
- const started = await coordinator.handlers['turn.resume.start']({
1747
+ const started = await coordinator.startTurnResumeWithValidation({
1710
1748
  sessionId: assignment.targetSessionId,
1711
1749
  turnId: targetTurnId,
1712
1750
  sourceRunId: plan.result.sourceRunId,
1713
1751
  sourceRuntimeEventHighWater: plan.result.sourceRuntimeEventHighWater,
1714
- }, context);
1752
+ }, context, assertTargetExecutionReady);
1715
1753
  if (!started.ok) {
1716
1754
  throw new WorkHubActionEffectFailure(started.error.code, started.error.message);
1717
1755
  }
@@ -2054,6 +2092,9 @@ export async function createExecutionRuntimeHostComposition(context, options = {
2054
2092
  recovery: { state: () => pluginPlatform.recover() },
2055
2093
  drain: [() => pluginPlatform.beginDrain()],
2056
2094
  close: [() => pluginPlatform.close()],
2095
+ releaseConnection: [
2096
+ (connectionId) => pluginPlatformCoordinator.releaseConnection(connectionId),
2097
+ ],
2057
2098
  }),
2058
2099
  createRuntimeHostDomainModule({
2059
2100
  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
  }
@@ -22,6 +22,7 @@ import { dirname, join, posix } from 'node:path';
22
22
  import { isCanonicalExtensionId } from '@maka/runtime/plugin-runtime';
23
23
  import { exportExtensionBundle, extensionPackageContentDigest, materializeExtensionPackage, } from './extension-bundle.js';
24
24
  import { EXTENSION_PACKAGE_MANIFEST_FILE, loadExtensionPackageManifest, } from './extension-package-manifest.js';
25
+ import { PLUGIN_CLIENT_BUNDLE_MAX_BYTES } from '../protocol/plugin-platform.js';
25
26
  const STORE_DIRECTORY = 'plugin-packages-v2';
26
27
  const MAX_FILES = 256;
27
28
  const MAX_FILE_BYTES = 8 * 1024 * 1024;
@@ -392,17 +393,32 @@ async function decodePackage(root, files) {
392
393
  const manifest = await loadExtensionPackageManifest(root);
393
394
  if (!manifest)
394
395
  throw invalid(`Plugin package is missing ${EXTENSION_PACKAGE_MANIFEST_FILE}`);
395
- if (!manifest.runtime?.entry)
396
- throw invalid('Plugin package has no trusted Runtime entry');
397
- if (!files.some((file) => file.path === manifest.runtime.entry)) {
396
+ if (!manifest.runtime?.entry && !manifest.client?.entry) {
397
+ throw invalid('Plugin package has no Runtime or Client entry');
398
+ }
399
+ if (manifest.runtime && !files.some((file) => file.path === manifest.runtime.entry)) {
398
400
  throw invalid(`Plugin Runtime entry does not exist: ${manifest.runtime.entry}`);
399
401
  }
402
+ if (manifest.client && !files.some((file) => file.path === manifest.client.entry)) {
403
+ throw invalid(`Plugin Client entry does not exist: ${manifest.client.entry}`);
404
+ }
405
+ if (manifest.client) {
406
+ const clientBytes = files.find((file) => file.path === manifest.client.entry)?.content
407
+ .byteLength;
408
+ if (clientBytes === 0) {
409
+ throw invalid(`Plugin Client entry is empty: ${manifest.client.entry}`);
410
+ }
411
+ if (clientBytes !== undefined && clientBytes > PLUGIN_CLIENT_BUNDLE_MAX_BYTES) {
412
+ throw invalid(`Plugin Client entry exceeds its size limit: ${manifest.client.entry}`);
413
+ }
414
+ }
400
415
  if (manifest.composition && !files.some((file) => file.path === manifest.composition.patch)) {
401
416
  throw invalid(`Plugin Composition patch does not exist: ${manifest.composition.patch}`);
402
417
  }
403
418
  return Object.freeze({
404
419
  manifest,
405
- entry: manifest.runtime.entry,
420
+ ...(manifest.runtime ? { entry: manifest.runtime.entry } : {}),
421
+ ...(manifest.client ? { clientEntry: manifest.client.entry } : {}),
406
422
  contentDigest: extensionPackageContentDigest(files),
407
423
  });
408
424
  }
@@ -501,7 +517,8 @@ function freezeInstalled(root, decoded) {
501
517
  extensionId: decoded.manifest.id,
502
518
  contentDigest: decoded.contentDigest,
503
519
  root,
504
- entry: join(root, ...decoded.entry.split('/')),
520
+ ...(decoded.entry ? { entry: join(root, ...decoded.entry.split('/')) } : {}),
521
+ ...(decoded.clientEntry ? { clientEntry: join(root, ...decoded.clientEntry.split('/')) } : {}),
505
522
  manifest: decoded.manifest,
506
523
  });
507
524
  }
@@ -17,8 +17,9 @@
17
17
  * under the License.
18
18
  */
19
19
  import { JsonArrayPageBudget } from './json-array-page-budget.js';
20
- import { createHash } from 'node:crypto';
20
+ import { createHash, randomUUID } from 'node:crypto';
21
21
  import { MakaPluginRuntimeError, } from '@maka/runtime/plugin-runtime';
22
+ import { PluginClientBridgeError, } from '@maka/runtime/plugin-client-bridge-service';
22
23
  import { PLUGIN_PLATFORM_QUERY_RESULT_MAX_BYTES } from '../protocol/plugin-platform.js';
23
24
  import { ExtensionBundleError } from './extension-bundle.js';
24
25
  import { ExtensionPackageManifestError } from './extension-package-manifest.js';
@@ -28,7 +29,14 @@ import { PluginPackageStoreError } from './plugin-package-store.js';
28
29
  import { HostPluginPlatformError } from './plugin-platform.js';
29
30
  export class HostPluginPlatformCoordinator {
30
31
  platform;
32
+ #streams = new Map();
33
+ #pendingStreamOpens = new Map();
31
34
  handlers = {
35
+ 'plugin.client.query': (input) => this.#client(input),
36
+ 'plugin.client.remote.call': (input, context) => this.#remoteCall(input, context),
37
+ 'plugin.client.remote.stream.open': (input, context) => this.#remoteStreamOpen(input, context),
38
+ 'plugin.client.remote.stream.next': (input, context) => this.#remoteStreamNext(input, context),
39
+ 'plugin.client.remote.stream.close': (input, context) => this.#remoteStreamClose(input, context),
32
40
  'plugin.platform.query': (input) => this.#query(input),
33
41
  'plugin.package.install': (input) => this.#install(input),
34
42
  'plugin.package.uninstall': (input) => this.#uninstall(input),
@@ -40,6 +48,109 @@ export class HostPluginPlatformCoordinator {
40
48
  constructor(platform) {
41
49
  this.platform = platform;
42
50
  }
51
+ releaseConnection(connectionId) {
52
+ for (const [streamId, stream] of this.#streams) {
53
+ if (stream.connectionId !== connectionId)
54
+ continue;
55
+ this.#streams.delete(streamId);
56
+ void stream.binding.close().catch(() => undefined);
57
+ }
58
+ }
59
+ async #remoteCall(input, context) {
60
+ try {
61
+ return {
62
+ ok: true,
63
+ result: { value: await this.platform.invokeClientRemote(input, context.inputClosedSignal) },
64
+ };
65
+ }
66
+ catch (error) {
67
+ return failure(error);
68
+ }
69
+ }
70
+ async #remoteStreamOpen(input, context) {
71
+ const connectionId = context.connectionId;
72
+ const active = [...this.#streams.values()].filter((stream) => stream.connectionId === connectionId).length;
73
+ const pending = this.#pendingStreamOpens.get(connectionId) ?? 0;
74
+ if (active + pending >= 32) {
75
+ return failed('operation_conflict', 'Plugin Client Remote stream limit reached');
76
+ }
77
+ this.#pendingStreamOpens.set(connectionId, pending + 1);
78
+ try {
79
+ const binding = await this.platform.openClientRemoteStream(input, context.inputClosedSignal);
80
+ const streamId = randomUUID();
81
+ this.#streams.set(streamId, { connectionId, binding, reading: false });
82
+ return { ok: true, result: { streamId } };
83
+ }
84
+ catch (error) {
85
+ return failure(error);
86
+ }
87
+ finally {
88
+ const remaining = (this.#pendingStreamOpens.get(connectionId) ?? 1) - 1;
89
+ if (remaining === 0)
90
+ this.#pendingStreamOpens.delete(connectionId);
91
+ else
92
+ this.#pendingStreamOpens.set(connectionId, remaining);
93
+ }
94
+ }
95
+ async #remoteStreamNext(input, context) {
96
+ const stream = this.#ownedStream(input.streamId, context.connectionId);
97
+ if (!stream)
98
+ return failed('not_found', 'Plugin Client Remote stream is unavailable');
99
+ if (stream.reading) {
100
+ return failed('operation_conflict', 'Plugin Client Remote stream already has an active pull');
101
+ }
102
+ stream.reading = true;
103
+ try {
104
+ const result = await stream.binding.next();
105
+ if (result.done) {
106
+ this.#streams.delete(input.streamId);
107
+ return { ok: true, result: { done: true } };
108
+ }
109
+ return { ok: true, result: { done: false, value: result.value } };
110
+ }
111
+ catch (error) {
112
+ this.#streams.delete(input.streamId);
113
+ await stream.binding.close().catch(() => undefined);
114
+ return failure(error);
115
+ }
116
+ finally {
117
+ stream.reading = false;
118
+ }
119
+ }
120
+ async #remoteStreamClose(input, context) {
121
+ // End-of-stream and generation retirement may have already released it.
122
+ // An existing stream remains strictly owned by its connection.
123
+ const stream = this.#streams.get(input.streamId);
124
+ if (!stream)
125
+ return { ok: true, result: { streamId: input.streamId } };
126
+ if (stream.connectionId !== context.connectionId)
127
+ return failed('not_found', 'Plugin Client Remote stream is unavailable');
128
+ this.#streams.delete(input.streamId);
129
+ try {
130
+ await stream.binding.close();
131
+ return { ok: true, result: { streamId: input.streamId } };
132
+ }
133
+ catch (error) {
134
+ return failure(error);
135
+ }
136
+ }
137
+ #ownedStream(streamId, connectionId) {
138
+ const stream = this.#streams.get(streamId);
139
+ return stream?.connectionId === connectionId ? stream : undefined;
140
+ }
141
+ async #client(input) {
142
+ try {
143
+ return {
144
+ ok: true,
145
+ result: await this.platform.read(async () => input.kind === 'snapshot'
146
+ ? this.platform.clientSnapshot()
147
+ : await this.platform.readClientBundle(input)),
148
+ };
149
+ }
150
+ catch (error) {
151
+ return failure(error);
152
+ }
153
+ }
43
154
  async #query(input) {
44
155
  try {
45
156
  return await this.platform.read(async () => {
@@ -210,6 +321,9 @@ function failure(error) {
210
321
  return failed('host_not_ready', error.message);
211
322
  if (error.code === 'stale_cursor')
212
323
  return failed('stale_cursor', error.message);
324
+ if (error.code === 'client_generation_conflict') {
325
+ return failed('operation_conflict', error.message);
326
+ }
213
327
  if (error.code === 'closed')
214
328
  return failed('host_draining', error.message);
215
329
  if (error.code === 'persistence_failed')
@@ -223,6 +337,13 @@ function failure(error) {
223
337
  return failure(error.cause);
224
338
  return failed('internal_failure', error.message);
225
339
  }
340
+ if (error instanceof PluginClientBridgeError) {
341
+ if (error.code === 'not_found')
342
+ return failed('not_found', error.message);
343
+ if (error.code === 'invalid_input')
344
+ return failed('invalid_request', error.message);
345
+ return failed('operation_conflict', error.message);
346
+ }
226
347
  if (error instanceof PluginPackageStoreError) {
227
348
  if (error.code === 'not_found')
228
349
  return failed('not_found', error.message);