@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.3-alpha.1

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 (107) hide show
  1. package/CONSUMER_GUIDE.md +73 -26
  2. package/package.json +6 -1
  3. package/src/agent/config.ts +2 -0
  4. package/src/agent/native-operations.ts +1 -0
  5. package/src/agent-session.ts +11 -2
  6. package/src/agent.ts +4 -1
  7. package/src/index.ts +2 -0
  8. package/src/native/capabilities.ts +2 -2
  9. package/src/native/connection.ts +1 -1
  10. package/src/native/controller.ts +2 -1
  11. package/src/native/host-config.ts +2 -0
  12. package/src/native/host.ts +10 -0
  13. package/src/native/mcp.ts +47 -0
  14. package/src/native/recovery.ts +8 -7
  15. package/src/native/reminders/routine-guard.ts +4 -3
  16. package/src/native/reminders/routine-wire.ts +1 -1
  17. package/src/native-harness/README.md +58 -1
  18. package/src/native-harness/package.json +4 -0
  19. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  20. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  21. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  22. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  23. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  24. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  25. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  26. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  27. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  28. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  29. package/src/native-harness/src/capabilities/context/instructions.d.ts +4 -0
  30. package/src/native-harness/src/capabilities/context/load-instructions.ts +9 -10
  31. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  32. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  33. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  34. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  35. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  36. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  37. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  38. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  39. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  40. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  41. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  42. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  43. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  44. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  45. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  46. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  47. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  48. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  49. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  50. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  51. package/src/native-harness/src/contracts/agent.ts +3 -1
  52. package/src/native-harness/src/contracts/attachments.ts +62 -0
  53. package/src/native-harness/src/contracts/config-permissions.ts +13 -4
  54. package/src/native-harness/src/contracts/context.ts +1 -1
  55. package/src/native-harness/src/contracts/events.ts +2 -2
  56. package/src/native-harness/src/contracts/loop.ts +3 -3
  57. package/src/native-harness/src/contracts/mcp.ts +22 -0
  58. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  59. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  60. package/src/native-harness/src/contracts/protocol.ts +20 -4
  61. package/src/native-harness/src/contracts/session-file.ts +2 -1
  62. package/src/native-harness/src/contracts/session.ts +6 -1
  63. package/src/native-harness/src/contracts/storage.ts +23 -5
  64. package/src/native-harness/src/contracts/tools.ts +2 -0
  65. package/src/native-harness/src/contracts/web.ts +16 -0
  66. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  67. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  68. package/src/native-harness/src/index.ts +43 -11
  69. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  70. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  71. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  72. package/src/native-harness/src/interfaces/client.ts +8 -2
  73. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  74. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  75. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  76. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  77. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  78. package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
  79. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
  80. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  81. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  82. package/src/native-harness/src/kernel/channels.ts +19 -11
  83. package/src/native-harness/src/kernel/loop.ts +1 -1
  84. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  85. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  86. package/src/native-harness/src/runtime/config/paths.ts +3 -2
  87. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  88. package/src/native-harness/src/state/storage/archive.ts +95 -12
  89. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  90. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  91. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  92. package/src/native-harness/src/state/storage/engine.ts +194 -34
  93. package/src/native-harness/src/state/storage/inference.ts +30 -2
  94. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  95. package/src/native-harness/src/state/storage/memory.ts +18 -3
  96. package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
  97. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  98. package/src/native-harness/src/state/storage/sqlite.ts +51 -10
  99. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  100. package/src/native-harness/src/testing.ts +150 -55
  101. package/src/native-harness/src/util/attachment-input.ts +42 -0
  102. package/src/native-harness/src/util/config.ts +59 -12
  103. package/src/native-harness/src/util/mcp-config.ts +102 -0
  104. package/src/native-harness/src/util/web-config.ts +34 -0
  105. package/src/native-harness/src/util/web-usage.ts +33 -0
  106. package/src/steering/combine.ts +1 -0
  107. package/src/steering/contracts.ts +3 -0
package/CONSUMER_GUIDE.md CHANGED
@@ -1153,6 +1153,19 @@ environment, or use a scripted model with a local JSONL scenario for offline
1153
1153
  development. Keep the harness home on durable storage. Backend kind stays fixed
1154
1154
  across a conversation's mode changes and handoffs.
1155
1155
 
1156
+ ### Compiled launchers
1157
+
1158
+ A compiled Bun application can import `serve(home)` from
1159
+ `@qlairoslabs/acp-client/native-harness` and call it from its own subprocess
1160
+ command. For example, route `agents __native-harness serve --home <directory>`
1161
+ to `await serve(directory)` in the application, then set `harness.command` to
1162
+ `[process.execPath, "__native-harness", "serve", "--home", directory]`.
1163
+ Handle that command before normal application startup and keep stdout reserved
1164
+ for the harness protocol. The command override includes all arguments, so pass
1165
+ the same directory as `harness.home`.
1166
+
1167
+ ### Configuration
1168
+
1156
1169
  ```ts
1157
1170
  import { Agent, ADAPTERS, type AgentHarnessConfig } from "@qlairoslabs/acp-client";
1158
1171
 
@@ -1769,41 +1782,75 @@ harness: {
1769
1782
  but has no recorded result (crash, lost connection, interrupt) is
1770
1783
  `interrupted` with `effect: "unknown"`. It is never run again automatically.
1771
1784
 
1772
- Native conversations do not support attaching ACP `mcpServers`. To use an
1773
- MCP tool, connect the MCP client in your host application and register a
1774
- native function that calls it. Supply the tool description and input schema
1775
- and allow the wrapper by its registered name in `harness.config.policies`.
1785
+ #### Native MCP servers
1786
+
1787
+ Configure native servers in `harness.config.mcpServers`. The harness
1788
+ supports stdio and Streamable HTTPS. `agent.nativeMcpStatus()` reports
1789
+ negotiated transports and per-server state. Restart results include
1790
+ the same MCP status snapshot. A stopped host reports its last snapshot
1791
+ as stale.
1792
+
1793
+ The npm package installs the MCP SDK and Undici as optional dependencies.
1794
+ If an install omits them, the configured MCP entries report
1795
+ `state: "unavailable"`, with `reason: "discovery"` for stdio or
1796
+ `reason: "connect"` for HTTPS. These statuses describe the failed stage
1797
+ without exposing credential values. Install the optional dependencies to
1798
+ use MCP. Other native features still work without them.
1799
+ A failing MCP server leaves the harness running. A plain HTTP 500 on discovery marks that entry unavailable, and on a tool
1800
+ call the model sees one sanitized `mcp_uncertain` result with no replay. Other channels and servers keep working.
1776
1801
 
1777
1802
  ```ts
1778
- import { FunctionError, type NativeFunctionsConfig } from "@qlairoslabs/acp-client";
1803
+ import type { AgentHarnessConfig } from "@qlairoslabs/acp-client";
1779
1804
 
1780
- export function orderTools(
1781
- callMcpTool: (name: string, args: Record<string, unknown>, signal: AbortSignal) =>
1782
- Promise<{ content: unknown[]; isError?: boolean }>,
1783
- ): NativeFunctionsConfig {
1805
+ export function withNativeMcp(
1806
+ config: AgentHarnessConfig["config"],
1807
+ getAuthorization: () => Promise<string>,
1808
+ ) {
1784
1809
  return {
1785
- tools: {
1786
- lookup: {
1787
- description: "Look up an order",
1788
- parameters: {
1789
- type: "object",
1790
- properties: { id: { type: "string" } },
1791
- required: ["id"],
1792
- additionalProperties: false,
1793
- },
1794
- async handler(args, { signal }) {
1795
- const result = await callMcpTool("lookup_order", args, signal);
1796
- if (result.isError) throw new FunctionError("mcp_tool_error", "Order lookup failed");
1797
- return result.content;
1798
- },
1810
+ config: {
1811
+ ...config,
1812
+ defaultPolicy: "guest",
1813
+ policies: {
1814
+ owner: { fallback: "allow", tools: {}, mcp: "allow" },
1815
+ guest: { fallback: "allow", tools: {}, mcp: "deny" },
1816
+ },
1817
+ mcpServers: {
1818
+ docs: { transport: "stdio", command: "/app/bin/docs-mcp", args: [] },
1819
+ account: { transport: "http", endpoint: "https://example.com/mcp",
1820
+ headers: { Authorization: { runtime: true } } },
1799
1821
  },
1822
+ limits: { ...config.limits, mcpCallTimeoutMs: 5_000 },
1800
1823
  },
1801
- };
1824
+ mcpRuntimeHeaders: async () => ({ account: { Authorization: await getAuthorization() } }),
1825
+ } satisfies Pick<AgentHarnessConfig, "config" | "mcpRuntimeHeaders">;
1802
1826
  }
1803
1827
  ```
1804
1828
 
1805
- Pass the returned object as `harness.functions`. The host owns the MCP
1806
- connection lifecycle and forwards cancellation through its client library.
1829
+ Merge those fields into the Agent's `harness` settings. Only the trusted
1830
+ owner supplies `mcpRuntimeHeaders`. The callback runs for every
1831
+ executable open or create request, including retry, reconnect and restart.
1832
+ It can resolve refreshed credentials. Header names are case-insensitive.
1833
+ The encoded runtime headers are limited to 8 KiB total and 2 KiB per value.
1834
+ Larger material fails locally with `mcp_runtime_headers_too_large`.
1835
+ Missing or empty material disables that server entry before it connects,
1836
+ while other servers can still start. Keep credentials out of configuration,
1837
+ prompt content and metadata. Runtime header values are never persisted.
1838
+
1839
+ On an attributed prompt, the trusted caller can select an existing policy
1840
+ for that input with `conversation.promptFrom({ participantId, text,
1841
+ nativePolicy: "guest" })`. Object-form `prompt` accepts `nativePolicy` too.
1842
+ When the caller omits it, the harness uses the channel's selected policy,
1843
+ then the session default. Omitting `nativePolicy` denies MCP only when that
1844
+ fallback policy has no MCP grant. An owner channel still needs an explicit guest
1845
+ policy on guest input. Participant kind, sender ID, display name and text
1846
+ never grant MCP access. Do not populate `nativePolicy` from participant input.
1847
+
1848
+ The `mcp` grant covers all `mcp__` tools for that named policy. Every
1849
+ taken or inherited contributing policy must explicitly allow MCP. A
1850
+ mixed owner and guest turn, or a policy with no `mcp` value, denies it.
1851
+ The local deterministic fixtures verify this transport and policy wiring.
1852
+ Approval behavior in deployments using agents-tools or door integrations
1853
+ requires separate acceptance.
1807
1854
 
1808
1855
  Tool changes need a running harness: `revokeTool` and the others fail with
1809
1856
  `HarnessUnavailableError` while it is stopped.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.1-alpha.1",
3
+ "version": "0.13.3-alpha.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -59,6 +59,7 @@
59
59
  "./repl": "./src/repl/index.ts",
60
60
  "./degraded": "./src/degraded/index.ts",
61
61
  "./parser": "./src/parser/index.ts",
62
+ "./native-harness": "./src/native-harness/src/interfaces/cli/serve.ts",
62
63
  "./cli": "./src/cli/index.ts"
63
64
  },
64
65
  "bin": {
@@ -81,6 +82,10 @@
81
82
  "@agentclientprotocol/sdk": "0.25.1",
82
83
  "@xterm/headless": "^6.0.0"
83
84
  },
85
+ "optionalDependencies": {
86
+ "@modelcontextprotocol/sdk": "1.31.0",
87
+ "undici": "7.29.0"
88
+ },
84
89
  "devDependencies": {
85
90
  "@types/bun": "latest",
86
91
  "typescript": "^5"
@@ -116,6 +116,8 @@ export interface AgentHarnessConfig {
116
116
  readonly idleStopWindowMs?: number;
117
117
  /** The harness configuration, sent on every open. */
118
118
  readonly config: import("../native/reminders/routine-wire.ts").RoutineConfigInput;
119
+ /** Fresh secret material for each executable native harness open. */
120
+ readonly mcpRuntimeHeaders?: import("../native/mcp.ts").McpRuntimeHeadersProvider;
119
121
  /** The harness home, a path in the harness's environment. It must survive process restarts. */
120
122
  readonly home: string;
121
123
  /** How to start the harness server. Defaults to this package's harness in `serve --stdio` mode. */
@@ -36,4 +36,5 @@ export type NativeRestartResult = NativeRestartPreview & {
36
36
  readonly interruptedTurns: readonly { channel: string; turnId: string }[];
37
37
  readonly conversations: readonly { id: AgentConversationId; outcome: "reconnected" | "deferred" | "failed" }[];
38
38
  readonly error?: unknown;
39
+ readonly mcp?: import("../native/mcp.ts").NativeMcpStatus;
39
40
  };
@@ -1,3 +1,5 @@
1
+ import { NativeController } from "./native/controller.ts";
2
+ import type { NativeInputPolicy } from "./native/mcp.ts";
1
3
  import { protocolMethod } from "./persistence/protocol-method.ts";
2
4
  import { ReminderError } from "./native/reminders/schedule.ts";
3
5
  // AgentConversation — one durable conversation and the library's compatibility front
@@ -262,6 +264,8 @@ export interface AgentConversationPromptInput {
262
264
  readonly delivery?: PromptDelivery;
263
265
  /** Awaited before dispatch with this prompt's message ID. A rejection prevents dispatch. */
264
266
  readonly beforeDispatch?: (messageId: string) => Promise<void>;
267
+ /** Existing native policy selected by the trusted caller for this input. */
268
+ readonly nativePolicy?: NativeInputPolicy;
265
269
  }
266
270
 
267
271
  export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
@@ -1877,7 +1881,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1877
1881
  ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1878
1882
  : this.enqueuePrompt(
1879
1883
  promptInputText(input), "prompt", input.handlers, input.attachments,
1880
- undefined, input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch,
1884
+ undefined, input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch, input.nativePolicy,
1881
1885
  );
1882
1886
  }
1883
1887
 
@@ -1915,7 +1919,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1915
1919
  if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1916
1920
  return this.enqueuePrompt(
1917
1921
  promptInputText(input), "prompt", input.handlers, input.attachments,
1918
- input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch,
1922
+ input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch, input.nativePolicy,
1919
1923
  );
1920
1924
  }
1921
1925
  const participantId = input;
@@ -1939,6 +1943,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1939
1943
  delivery?: PromptDelivery,
1940
1944
  messageParts?: readonly MessagePart[],
1941
1945
  beforeDispatch?: AgentConversationPromptInput["beforeDispatch"],
1946
+ nativePolicy?: NativeInputPolicy,
1942
1947
  ): PromptHandle {
1943
1948
  const id = this.mintTurnId();
1944
1949
  const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
@@ -1949,6 +1954,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
1949
1954
  let stableConsumerMetadata: PersistenceJsonValue | undefined;
1950
1955
  try {
1951
1956
  this.assertPromptable();
1957
+ if (nativePolicy !== undefined && !(this.controller instanceof NativeController)) {
1958
+ throw new Error("nativePolicy requires a native conversation");
1959
+ }
1952
1960
  stableConsumerMetadata = snapshotConsumerMetadata(consumerMetadata, Boolean(this.ownerLifecycle));
1953
1961
  } catch (error) {
1954
1962
  reject(error);
@@ -1969,6 +1977,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1969
1977
  attachments,
1970
1978
  messageParts,
1971
1979
  beforeDispatch,
1980
+ ...(nativePolicy === undefined ? {} : { nativePolicy }),
1972
1981
  resolve: (result) => {
1973
1982
  this.acceptedMessages.delete(id);
1974
1983
  // Settled as cancelled before any turn took it: withdrawn (the tracker ignores it once taken).
package/src/agent.ts CHANGED
@@ -520,7 +520,8 @@ export class Agent {
520
520
  const functions = options.functions !== undefined && this.wrapNativeFunctions
521
521
  ? this.wrapNativeFunctions(options.functions ?? undefined) : options.functions;
522
522
  await host.restartForAgent({ ...options, signal, functions }, interruptedTurns);
523
- result = { ...preview, kind: "restarted", interruptedTurns, conversations: preview.conversationIds.map(id =>
523
+ const mcp = host.mcpSnapshot();
524
+ result = { ...preview, kind: "restarted", interruptedTurns, mcp, conversations: preview.conversationIds.map(id =>
524
525
  ({ id, outcome: host.channel(id) ? "reconnected" : "deferred" })) };
525
526
  } catch (error) {
526
527
  result = { ...preview, kind: "restart_failed", interruptedTurns, error,
@@ -533,6 +534,8 @@ export class Agent {
533
534
  })().finally(() => { this.nativeRestart = undefined; });
534
535
  }
535
536
 
537
+ nativeMcpStatus() { return this.nativeOperationHost().mcpStatus(); }
538
+
536
539
  readonly channelSettingsLive = channelSettingsLive;
537
540
 
538
541
  async applyNativeChannelSettings(id: AgentConversationId, settings: NativeChannelSettings): Promise<NativeChannelSettingsResult> {
package/src/index.ts CHANGED
@@ -805,3 +805,5 @@ export { ReminderError } from "./native/reminders/schedule.ts";
805
805
  export type { ReminderErrorCode, ReminderSchedule, ReminderScheduleInput } from "./native/reminders/schedule.ts";
806
806
  export type { Reminder } from "./persistence/reminders.ts";
807
807
  export type { ReminderCreate, ReminderEdit, ReminderView, ReminderEvent } from "./native/reminders/service.ts";
808
+
809
+ export type { McpRuntimeHeaders, McpRuntimeHeadersProvider, NativeInputPolicy, NativeMcpStatus } from "./native/mcp.ts";
@@ -1,6 +1,6 @@
1
1
  import type { ConversationCapabilities } from "../conversation-controller/capabilities.ts";
2
2
 
3
- export function nativeConversationCapabilities(reminders = true, routines = false): ConversationCapabilities {
3
+ export function nativeConversationCapabilities(reminders = true, routines = false, mcp?: import("./mcp.ts").NativeMcpStatus["capabilities"]): ConversationCapabilities {
4
4
  return {
5
5
  nativeSteering: true,
6
6
  reminders,
@@ -11,7 +11,7 @@ export function nativeConversationCapabilities(reminders = true, routines = fals
11
11
  backend: {
12
12
  loadSession: false, forkSession: false, listSessions: false,
13
13
  media: { image: false, audio: false, file: false },
14
- mcpServers: { stdio: false, http: false, sse: false },
14
+ mcpServers: mcp ?? { stdio: false, http: false, sse: false },
15
15
  },
16
16
  };
17
17
  }
@@ -30,7 +30,7 @@ export async function launchNativeConnection(config: NativeHarnessHostConfig, lo
30
30
  void (async () => {
31
31
  // Diagnostics only: the protocol is on stdout.
32
32
  const text = await new Response(child.stderr).text().catch(() => "");
33
- if (text.trim()) log.warn("native_harness_stderr", { text: text.slice(-4000) });
33
+ if (text.trim()) log.warn("native_harness_stderr", config.mcpRuntimeHeaders ? { redacted: true } : { text: text.slice(-4000) });
34
34
  })();
35
35
  let notify: (event: ReminderNotification) => void = () => {};
36
36
  const transport = createStdioTransport({
@@ -214,7 +214,7 @@ export class NativeController implements ConversationController, ChannelPort {
214
214
  }
215
215
  subscribeUsageUpdate(_listener: UsageListener): () => void { return () => undefined; }
216
216
  get currentSessionId(): string | null { return this.#host.sessionId; }
217
- get conversationCapabilities(): ConversationCapabilities { return nativeConversationCapabilities(this.#host.reminderSync?.supported, this.#host.reminderSync?.routineAdmission.available); }
217
+ get conversationCapabilities(): ConversationCapabilities { return nativeConversationCapabilities(this.#host.reminderSync?.supported, this.#host.reminderSync?.routineAdmission.available, this.#host.capabilities?.mcpServers); }
218
218
 
219
219
  receiptOf(messageId: string): "delivered" | "seen" | undefined { return this.#receipts.get(messageId); }
220
220
 
@@ -250,6 +250,7 @@ export class NativeController implements ConversationController, ChannelPort {
250
250
  channel: this.#channel,
251
251
  sender: message.participantId ?? this.#config.defaultSender ?? "user",
252
252
  text: message.text,
253
+ ...(message.nativePolicy === undefined ? {} : { policy: message.nativePolicy }),
253
254
  });
254
255
  }
255
256
  }
@@ -29,6 +29,8 @@ export interface NativeHarnessHostConfig {
29
29
  readonly sessionId: string;
30
30
  /** Sent on every open. Session configuration is fixed while the session is open. */
31
31
  readonly config: RoutineConfigInput;
32
+ /** Fresh secret material for each executable native harness open. */
33
+ readonly mcpRuntimeHeaders?: import("./mcp.ts").McpRuntimeHeadersProvider;
32
34
  /** The harness home, a path in the harness's environment. Must survive process restarts. */
33
35
  readonly home: string;
34
36
  /** How to start the harness server; defaults to this package's harness in `serve --stdio` mode. */
@@ -522,6 +522,7 @@ export class NativeHarnessHost {
522
522
  signal.throwIfAborted();
523
523
 
524
524
  const status = await client.status();
525
+ if (status.mcpServers === undefined && opened.mcpServers !== undefined) status.mcpServers = opened.mcpServers;
525
526
  signal.throwIfAborted();
526
527
  const view: LoadResult = { status, items: [], turns: [], messages: [] };
527
528
  const submissions = this.records.submissions();
@@ -859,6 +860,15 @@ export class NativeHarnessHost {
859
860
  return live;
860
861
  }
861
862
 
863
+ async mcpStatus(): Promise<import("./mcp.ts").NativeMcpStatus> {
864
+ const { session, stale } = await this.operatorStatus();
865
+ return this.mcpSnapshot(stale, session);
866
+ }
867
+
868
+ mcpSnapshot(stale = this.#state !== "running", session = this.#lastStatus): import("./mcp.ts").NativeMcpStatus {
869
+ return { capabilities: this.#capabilities?.mcpServers, servers: session?.mcpServers, stale };
870
+ }
871
+
862
872
  async operatorStatus() {
863
873
  const connection = this.#connection;
864
874
  let confirmed = false;
@@ -0,0 +1,47 @@
1
+ import { HarnessClientError, type CreateParams, type InitializeResult, type PushParams, type StatusResult } from "../native-harness/src/client.ts";
2
+ import { codeOf } from "./errors.ts";
3
+
4
+ export type NativeInputPolicy = NonNullable<PushParams["item"]["policy"]>;
5
+ export type McpRuntimeHeaders = NonNullable<CreateParams["mcpRuntimeHeaders"]>;
6
+ export type McpRuntimeHeadersProvider = () => McpRuntimeHeaders | Promise<McpRuntimeHeaders>;
7
+ export type NativeMcpStatus = {
8
+ readonly capabilities?: InitializeResult["description"]["capabilities"]["mcpServers"];
9
+ readonly servers?: StatusResult["mcpServers"];
10
+ readonly stale: boolean;
11
+ };
12
+
13
+ const runtimeHeaderLimits = { totalBytes: 8 * 1024, valueBytes: 2 * 1024 };
14
+
15
+ function validateRuntimeHeaderSize(material: McpRuntimeHeaders): void {
16
+ const tooLarge = () => new HarnessClientError("mcp_runtime_headers_too_large",
17
+ "Native MCP runtime headers exceed the 8 KiB total or 2 KiB per-value limit");
18
+ for (const headers of Object.values(material)) {
19
+ for (const value of Object.values(headers)) {
20
+ if (Buffer.byteLength(value) > runtimeHeaderLimits.valueBytes) throw tooLarge();
21
+ }
22
+ }
23
+ // Count JSON framing, names and escape expansion as well as the values.
24
+ if (Buffer.byteLength(JSON.stringify(material)) > runtimeHeaderLimits.totalBytes) throw tooLarge();
25
+ }
26
+
27
+ export async function executableMcpOpen<T>(provider: McpRuntimeHeadersProvider | undefined, signal: AbortSignal,
28
+ send: (material?: McpRuntimeHeaders) => Promise<T>): Promise<T> {
29
+ if (!provider) return send();
30
+ let material: McpRuntimeHeaders;
31
+ try { material = await provider(); }
32
+ catch { throw new HarnessClientError("mcp_runtime_headers_failed", "Could not obtain native MCP runtime headers"); }
33
+ signal.throwIfAborted();
34
+ try { validateRuntimeHeaderSize(material); }
35
+ catch (error) {
36
+ if (codeOf(error) === "mcp_runtime_headers_too_large") throw error;
37
+ throw new HarnessClientError("mcp_runtime_headers_failed", "Could not encode native MCP runtime headers");
38
+ }
39
+ try { return await send(material); }
40
+ catch (error) {
41
+ const code = codeOf(error);
42
+ const allowed = ["not_found", "timeout", "transport_closed", "closed", "storage_failure", "invalid_config",
43
+ "invalid_params", "incompatible", "busy", "already_exists"];
44
+ throw new HarnessClientError(code && allowed.includes(code) ? code : "mcp_open_failed",
45
+ "Native harness executable open failed");
46
+ }
47
+ }
@@ -1,3 +1,4 @@
1
+ import { executableMcpOpen, type McpRuntimeHeadersProvider } from "./mcp.ts";
1
2
  import { activatesRoutine, RoutineAdmission } from "./reminders/routine-guard.ts";
2
3
  import type { ReminderChange } from "../persistence/reminders.ts";
3
4
  import type { ReminderSync } from "./reminders/sync.ts";
@@ -51,7 +52,7 @@ export async function readCompleteMessage(client: HarnessClient, messageId: stri
51
52
 
52
53
  /** The catalog and startup edits are installed before recovered work can start. */
53
54
  export async function openOrCreate(
54
- client: HarnessClient, config: { sessionId: string; config?: RoutineConfigInput },
55
+ client: HarnessClient, config: { sessionId: string; config?: RoutineConfigInput; mcpRuntimeHeaders?: McpRuntimeHeadersProvider },
55
56
  batch: PendingChannelChange[], tools: Parameters<HarnessClient["openSession"]>[0]["tools"], signal: AbortSignal, reminders?: ReminderSync,
56
57
  ) {
57
58
  const admission = reminders?.routineAdmission ?? new RoutineAdmission();
@@ -71,10 +72,12 @@ export async function openOrCreate(
71
72
  sessionId: config.sessionId, config: admission.configForOpen(config.config), ...changes,
72
73
  ...(staged.length ? { reminderChanges: staged } : {}),
73
74
  };
75
+ const send = (request: typeof params) => executableMcpOpen(config.mcpRuntimeHeaders, signal, material => {
76
+ const executable = { ...request, ...(material === undefined ? {} : { mcpRuntimeHeaders: material }) };
77
+ return create ? client.createSession({ ...executable, participants: [], channels: {} }) : client.openSession(executable);
78
+ });
74
79
  try {
75
- return create
76
- ? await client.createSession({ ...params, participants: [], channels: {} })
77
- : await client.openSession(params);
80
+ return await send(params);
78
81
  } catch (error) {
79
82
  const code = codeOf(error);
80
83
  if (staged.length && code === "storage_failure") {
@@ -103,9 +106,7 @@ export async function openOrCreate(
103
106
  const { reminderChanges: _rejected, ...unbatched } = params;
104
107
  let result: ReminderWireOpen;
105
108
  try {
106
- result = create
107
- ? await client.createSession({ ...unbatched, participants: [], channels: {} })
108
- : await client.openSession(unbatched);
109
+ result = await send(unbatched);
109
110
  } catch (retryError) {
110
111
  await reminders!.restoreStaged(originals);
111
112
  throw retryError;
@@ -48,14 +48,15 @@ export class RoutineAdmission {
48
48
  configForOpen(config: RoutineConfigInput | undefined): RoutineConfig | undefined {
49
49
  if (!config) return;
50
50
  const { limits, ...rest } = config;
51
- const configured = limits?.unattendedTurns;
52
- if (configured === undefined) return rest;
51
+ const { unattendedTurns: configured, ...otherLimits } = limits ?? {};
52
+ const retained = Object.keys(otherLimits).length ? { ...rest, limits: otherLimits } : rest;
53
+ if (configured === undefined) return retained;
53
54
  const value = configured === "unlimited" ? Number.MAX_SAFE_INTEGER : configured;
54
55
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
55
56
  throw new ReminderError("invalid_config", 'unattendedTurns must be a positive safe integer or "unlimited"');
56
57
  }
57
58
  if (!this.supported) throw new HarnessIncompatibleError("The native harness must support routines and unattendedTurnGuard to configure unattendedTurns");
58
- return this.bound === value ? rest : { ...rest, limits: { unattendedTurns: value } };
59
+ return this.bound === value ? retained : { ...rest, limits: { ...otherLimits, unattendedTurns: value } };
59
60
  }
60
61
 
61
62
  opened(opened: ReminderWireOpen): void {
@@ -17,5 +17,5 @@ export interface ReminderNegotiation {
17
17
  }
18
18
 
19
19
  export type RoutineConfigInput = Omit<ProtocolConfig, "limits"> & {
20
- limits?: { unattendedTurns: number | "unlimited" };
20
+ limits?: Omit<NonNullable<ProtocolConfig["limits"]>, "unattendedTurns"> & { unattendedTurns?: number | "unlimited" };
21
21
  };
@@ -24,7 +24,15 @@ work. Experiments live in [.res/sandbox/](.res/sandbox/).
24
24
  This directory is an independent TypeScript and Bun project (Bun >= 1.3.5), with
25
25
  its own package manifest, lockfile and TypeScript configuration. It does not
26
26
  depend on the parent acp-client package. Development dependencies are TypeScript
27
- and Bun types; there are no runtime dependencies.
27
+ and Bun types. Managed image input additionally requires the optional local
28
+ `ffmpeg`, `ffprobe`, and Linux `prlimit` executables on `PATH`; general-file attachments do not.
29
+ Image input is offered only when the model configuration explicitly opts in
30
+ and all three executables are available. Both image processes run under a 1 GiB
31
+ address-space limit, a CPU limit, and a file-descriptor limit, with bounded
32
+ output and a cancellable timeout. Input is passed via an anonymous Linux temporary inode on stdin, with no named
33
+ copy left on disk; an O_TMPFILE-capable temporary filesystem is required.
34
+ They accept only pipe input; missing tools,
35
+ unsupported platforms, resource exhaustion, and invalid images fail closed.
28
36
 
29
37
  From this directory:
30
38
 
@@ -605,6 +613,28 @@ Run `bun test test/protocol.test.ts test/stdio.test.ts` for transport parity and
605
613
  framing/process lifecycle checks. Child stdin in Bun uses IPC and may require
606
614
  local IPC permissions in sandboxed environments. All scenarios are offline.
607
615
 
616
+ ### Managed attachments
617
+
618
+ Managed stdio sessions store files in `<home>/<sessionId>/media`; development
619
+ with an explicit `--db PATH` uses `PATH.media`. The paired web chat can upload
620
+ and download files, and memory-backed development uses a temporary media root.
621
+ The host can use `beginAttachment`, `writeAttachment`, `finalizeAttachment`,
622
+ `attachmentStatus`, `abortAttachment` and `readAttachment` on `HarnessClient`.
623
+ Chunks are at most 512 KiB decoded; each file is at most 20 MiB. Finalization
624
+ checks length and SHA-256 before committing ready metadata. A push may contain
625
+ ordered text and attachment references, including an attachment-only input.
626
+ Text-only pushes retain their existing retry identity.
627
+
628
+ Set `model.imageInput: true` explicitly to enable PNG, JPEG and WebP input
629
+ when the local validator is available. Initialize reports attachment protocol
630
+ support; create/open reports the effective image capability and limits. A
631
+ text-only model rejects an image push before acceptance. Ready files belong to
632
+ their uploading channel until a referenced message enters the shared timeline;
633
+ then timeline readers may download them. History and diagnostics contain
634
+ references and metadata, not image bytes. Complete session exports include
635
+ retained attachment bytes and fail if those bytes are missing or the bounded
636
+ archive cannot contain them.
637
+
608
638
  ## Consumer tools and host callbacks
609
639
 
610
640
  A host can register functions for the model to call
@@ -724,3 +754,30 @@ A stopped harness needs a host to reopen it before any due work can run.
724
754
 
725
755
  Run `bun test test/reminder-stdio.test.ts` from this package to verify cold
726
756
  open, replay, process death and the idle-stop fence with a scripted model.
757
+
758
+ Managed web tools are disabled until configured. `webSearch` accepts an Exa
759
+ backend; `webFetch` independently accepts Exa or direct HTTP. Exa resolves the
760
+ configured `apiKeyEnv` (default `EXA_API_KEY`) from the launching process at
761
+ executable open; configuration and exports store the variable name, never its
762
+ value. Direct HTTP needs no Exa credential. Both tools use the session's normal
763
+ tool policy and produce bounded JSON previews; inspect per-invocation provider
764
+ estimates separately from model token usage. See
765
+ [decision 0035](.res/decisions/0035-web-search-fetch.md) for transport limits,
766
+ address checks, cost recovery and defaults.
767
+
768
+ ### Managed MCP tools
769
+
770
+ Decision 0036 adds the optional `@modelcontextprotocol/sdk` 1.31.0 dependency
771
+ for executable sessions with configured MCP servers. Install the harness
772
+ package dependencies before running the feature. Set `mcpServers` in managed
773
+ configuration, with a direct executable, arguments and any explicit environment
774
+ references. Grant `mcp: "allow"` under the trusted owner policy. MCP defaults
775
+ to deny, including when any taken input contributes a policy without a grant.
776
+ An executable reopen discovers the configured server's tools again.
777
+
778
+ Streamable HTTPS uses an optional private Undici 7.29.0 dispatcher, with
779
+ endpoint binding and certificate validation. Use environment references or
780
+ runtime declarations for secret headers. The owning protocol caller supplies
781
+ runtime values on each executable create or reopen. Upstream launcher
782
+ acceptance is tracked separately. The offline fixtures do not establish the
783
+ approval behavior of agents-tools or the door.
@@ -20,5 +20,9 @@
20
20
  "devDependencies": {
21
21
  "@types/bun": "^1.3.0",
22
22
  "typescript": "^5"
23
+ },
24
+ "optionalDependencies": {
25
+ "@modelcontextprotocol/sdk": "1.31.0",
26
+ "undici": "7.29.0"
23
27
  }
24
28
  }
@@ -0,0 +1,42 @@
1
+ import type { AttachmentMetadata, InputPart } from "../../contracts/attachments.ts";
2
+ import { ATTACHMENT_LIMITS } from "../../contracts/attachments.ts";
3
+ import { mixedPartsSignature, validateMixedParts } from "./input.ts";
4
+
5
+ export class AttachmentAdmissionError extends Error {
6
+ constructor(readonly code: "item_conflict" | "not_found" | "unsupported_image" | "transfer_limit", message: string) { super(message); }
7
+ }
8
+
9
+ /** Called within the session owner's single transaction. `accept` must apply
10
+ * normal channel/lifecycle/policy checks and insert the item; `associate` must
11
+ * persist the ordered parts and links in that transaction. Existing identities
12
+ * are compared before checking lifecycle, file state or model capability. */
13
+ export function admitAttachmentInput<T>(input: { channel: string; identity: string; content: unknown; imageInput: boolean;
14
+ known: () => { identity: string; value: T } | undefined;
15
+ lookup: (id: string) => AttachmentMetadata | undefined;
16
+ accept: (identity: string, parts: readonly InputPart[]) => T;
17
+ associate: (value: T, parts: readonly InputPart[]) => void;
18
+ }): { value: T; duplicate: boolean } {
19
+ const parts = validateMixedParts(input.content);
20
+ // The caller's identity covers channel, sender and policy, while this suffix
21
+ // makes the exact ordered part boundaries part of that identity.
22
+ const identity = JSON.stringify([input.identity, mixedPartsSignature(parts)]);
23
+ const known = input.known();
24
+ if (known) {
25
+ if (known.identity !== identity) throw new AttachmentAdmissionError("item_conflict", "Item ID already identifies different input");
26
+ return { value: known.value, duplicate: true };
27
+ }
28
+ let images = 0, bytes = 0;
29
+ for (const part of parts) if (part.type === "attachment") {
30
+ const metadata = input.lookup(part.id);
31
+ if (!metadata || metadata.channel !== input.channel) throw new AttachmentAdmissionError("not_found", "Unknown attachment");
32
+ if (metadata.mediaType.startsWith("image/")) {
33
+ if (!input.imageInput) throw new AttachmentAdmissionError("unsupported_image", "Image input is unsupported");
34
+ images++; bytes += metadata.bytes;
35
+ }
36
+ }
37
+ if (images > ATTACHMENT_LIMITS.references || bytes > ATTACHMENT_LIMITS.imageBytesPerTurn)
38
+ throw new AttachmentAdmissionError("transfer_limit", "Input image budget exceeded");
39
+ const value = input.accept(identity, parts);
40
+ input.associate(value, parts);
41
+ return { value, duplicate: false };
42
+ }