@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.2-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 (105) hide show
  1. package/CONSUMER_GUIDE.md +60 -26
  2. package/package.json +5 -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/model/openrouter-stream.ts +80 -17
  30. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  31. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  32. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  33. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  34. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  35. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  36. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  37. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  38. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  39. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  40. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  41. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  42. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  43. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  44. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  45. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  46. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  47. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  48. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  49. package/src/native-harness/src/contracts/agent.ts +3 -1
  50. package/src/native-harness/src/contracts/attachments.ts +62 -0
  51. package/src/native-harness/src/contracts/config-permissions.ts +13 -4
  52. package/src/native-harness/src/contracts/context.ts +1 -1
  53. package/src/native-harness/src/contracts/events.ts +2 -2
  54. package/src/native-harness/src/contracts/loop.ts +3 -3
  55. package/src/native-harness/src/contracts/mcp.ts +22 -0
  56. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  57. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  58. package/src/native-harness/src/contracts/protocol.ts +20 -4
  59. package/src/native-harness/src/contracts/session-file.ts +2 -1
  60. package/src/native-harness/src/contracts/session.ts +6 -1
  61. package/src/native-harness/src/contracts/storage.ts +23 -5
  62. package/src/native-harness/src/contracts/tools.ts +2 -0
  63. package/src/native-harness/src/contracts/web.ts +16 -0
  64. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  65. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  66. package/src/native-harness/src/index.ts +43 -11
  67. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  68. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  69. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  70. package/src/native-harness/src/interfaces/client.ts +8 -2
  71. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  72. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  73. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  74. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  75. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  76. package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
  77. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
  78. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  79. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  80. package/src/native-harness/src/kernel/channels.ts +19 -11
  81. package/src/native-harness/src/kernel/loop.ts +1 -1
  82. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  83. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  84. package/src/native-harness/src/runtime/config/paths.ts +3 -2
  85. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  86. package/src/native-harness/src/state/storage/archive.ts +95 -12
  87. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  88. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  89. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  90. package/src/native-harness/src/state/storage/engine.ts +194 -34
  91. package/src/native-harness/src/state/storage/inference.ts +30 -2
  92. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  93. package/src/native-harness/src/state/storage/memory.ts +18 -3
  94. package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
  95. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  96. package/src/native-harness/src/state/storage/sqlite.ts +51 -10
  97. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  98. package/src/native-harness/src/testing.ts +150 -55
  99. package/src/native-harness/src/util/attachment-input.ts +42 -0
  100. package/src/native-harness/src/util/config.ts +59 -12
  101. package/src/native-harness/src/util/mcp-config.ts +102 -0
  102. package/src/native-harness/src/util/web-config.ts +34 -0
  103. package/src/native-harness/src/util/web-usage.ts +33 -0
  104. package/src/steering/combine.ts +1 -0
  105. package/src/steering/contracts.ts +3 -0
@@ -2,6 +2,7 @@ import type { ChannelInput } from "../../contracts/agent.ts";
2
2
  import type { ChannelOutputs } from "../../contracts/output.ts";
3
3
  import type { PersistentSession } from "../../contracts/session.ts";
4
4
  import { outputStream } from "./output.ts";
5
+ import { validateMixedParts } from "../../util/attachment-input.ts";
5
6
 
6
7
  type LocalSession = Pick<PersistentSession, "agent" | "subscribe">;
7
8
  /** Lifecycle operations for the process owner's local socket only. */
@@ -67,15 +68,23 @@ export function createChannelHandler(session: LocalSession, outputs?: ChannelOut
67
68
  let input: ChannelInput;
68
69
  try {
69
70
  const body = await request.json() as ChannelInput | null;
70
- if (!body || ![body.channelId, body.participantId, body.text].every(
71
+ if (!body || ![body.channelId, body.participantId].every(
71
72
  (value) => typeof value === "string" && value.trim().length > 0,
72
- )) throw new Error("Expected channelId, participantId and text as nonempty strings");
73
- input = { channelId: body.channelId, participantId: body.participantId, text: body.text };
73
+ )) throw new Error("Expected channelId and participantId as nonempty strings");
74
+ if (body.parts !== undefined) {
75
+ const parts = validateMixedParts(body.parts);
76
+ const text = parts.flatMap(part => part.type === "text" ? [part.text] : []).join("\n");
77
+ if (body.text !== undefined && body.text !== text) throw new Error("Text does not match ordered parts");
78
+ input = { channelId: body.channelId, participantId: body.participantId, text, parts };
79
+ } else {
80
+ if (typeof body.text !== "string" || !body.text.trim()) throw new Error("Expected nonempty text");
81
+ input = { channelId: body.channelId, participantId: body.participantId, text: body.text };
82
+ }
74
83
  } catch (error) {
75
84
  return Response.json({ error: String(error) }, { status: 400 });
76
85
  }
77
86
  const accepted = session.agent.send(input);
78
- if (!accepted.accepted) return Response.json({ error: accepted.error }, { status: accepted.code === "invalid_input" ? 400 : 503 });
87
+ if (!accepted.accepted) return Response.json({ error: accepted.error, code: accepted.code }, { status: accepted.code === "invalid_input" ? 400 : 409 });
79
88
  try { return Response.json({ answer: await reply(accepted.itemId) }); }
80
89
  catch (error) { return Response.json({ error: String(error) }, { status: 500 }); }
81
90
  };
@@ -1,3 +1,4 @@
1
+ import { attachmentView } from "../../contracts/attachments.ts";
1
2
  import { timelineMessageId as messageId } from "../../util/timeline-text.ts";
2
3
  import { messagePosition } from "../../util/message-position.ts";
3
4
  import type { PersistentSession } from "../../contracts/session.ts";
@@ -66,7 +67,7 @@ export function operatorRead(session: PersistentSession, method: string, p: Reco
66
67
  const page = readValue(storage.readTimeline({ kind: "replies", channel, turnIds: turns, direction: "newer", throughRevision: revision,
67
68
  exclusiveSeq: cursor ? sequence(cursor[4]) : undefined, limit: 50 })).value;
68
69
  const items = tracked?.items.map(item => ({ id: item.itemId, channel: item.channelId, kind: item.kind, sender: item.senderId, ...(item.externalSource === undefined ? {} : { externalSource: item.externalSource }),
69
- milestone: item.milestone, ...(item.policy ? { policy: item.policy } : {}), ...(item.turnId !== undefined ? { turnId: String(item.turnId) } : {}) })) ?? [];
70
+ milestone: item.milestone, ...(item.parts ? { parts: attachmentView(item.parts, storage.readManagedAttachment, { ownerChannel: channel! }) } : {}), ...(item.policy ? { policy: item.policy } : {}), ...(item.turnId !== undefined ? { turnId: String(item.turnId) } : {}) })) ?? [];
70
71
  const foundTurns = tracked?.turns.map(turnStatus) ?? [];
71
72
  const result = { revision, items, turns: foundTurns, unknownItemIds: inputIds.filter(id => !items.some(item => item.id === id)),
72
73
  unknownTurnIds: cursor ? [] : turns.map(String).filter(id => !foundTurns.some(turn => turn.turnId === id)),
@@ -96,11 +97,16 @@ export function operatorRead(session: PersistentSession, method: string, p: Reco
96
97
  const base = { channel: entry.channelId, turnId: String(entry.turnId), actor, position: position(entry) };
97
98
  const message = entry.message;
98
99
  const content = participant && message.role === "user" ? message.content.slice(`Participant: ${JSON.stringify(entry.from)}\n\n`.length) : message.content;
100
+ const parts = participant && message.role === "user" && message.parts ? message.parts.map(part => {
101
+ if (part.type === "text") return part;
102
+ const found = storage.readManagedAttachment ? readValue(storage.readManagedAttachment(part.id)).value : undefined;
103
+ return found?.timelineVisible ? { ...part, metadata: found.metadata } : { ...part, unavailable: true as const };
104
+ }) : [{ type: "text" as const, text: content }];
99
105
  const identity = { ...base, messageId: messageId(entry), ...(participant ? { itemId: entry.itemId } : {}) };
100
106
  const activity = { ...base, ...(entry.kind === "external_notice" ? { itemId: entry.itemId, externalSource: entry.externalSource } : {}), ...(entry.sourceChannelId ? { sourceChannel: entry.sourceChannelId } : {}),
101
107
  kind: entry.kind ?? (message.role === "tool" ? "tool_result" : message.role === "assistant" && !message.content ? "tool_call" : "assistant_message"),
102
108
  ...(message.role === "assistant" || participant ? { messageId: messageId(entry) } : {}) };
103
- let record: object = channel ? { ...identity, parts: [{ type: "text", text: content }] } : { ...activity, payload: message };
109
+ let record: object = channel ? { ...identity, parts } : { ...activity, payload: message.role === "user" && participant && message.parts ? { ...message, parts } : message };
104
110
  let bytes = Buffer.byteLength(JSON.stringify(record)) + 1;
105
111
  if (bytes > budget) {
106
112
  record = channel ? { ...identity, ...(participant ? { omitted: true } : { reference: true }) } : { ...activity, omitted: true,
@@ -1,3 +1,4 @@
1
+ import { attachmentView } from "../../contracts/attachments.ts";
1
2
  import { OperatorFault, operatorMethods, operatorRead, readValue } from "./operator.ts";
2
3
  import type { ProtocolEndpoint, RpcRequest, RpcResponse, RpcNotification, RpcSessionNotification, ProtocolConfig, Description, Subscription, DurableErrorCode } from "../../contracts/protocol.ts";
3
4
  import type { PersistentSession } from "../../contracts/session.ts";
@@ -18,15 +19,22 @@ import { ToolFault, createCallbackBridge, isToolMethod, toolMethods, toolRequest
18
19
  import { parseReminderBatch, parseReminderChange, parseReminderList, ReminderShapeError } from "../../runtime/reminder-validation.ts";
19
20
  import { REMINDER_LIMITS } from "../../util/reminder-schedule.ts";
20
21
  import type { ReminderChange, ReminderChangeResult, ReminderSessionEvent } from "../../contracts/reminders.ts";
22
+ import type { createManagedAttachmentService } from "../../capabilities/attachments/service.ts";
23
+ import { AttachmentServiceError } from "../../capabilities/attachments/service.ts";
24
+ import { UploadError } from "../../capabilities/attachments/upload.ts";
25
+ import { AttachmentReadError } from "../../capabilities/attachments/read.ts";
26
+ import { AttachmentInputError, validateMixedParts } from "../../util/attachment-input.ts";
27
+ import type { InputPart } from "../../contracts/attachments.ts";
28
+ import { ATTACHMENT_LIMITS } from "../../contracts/attachments.ts";
21
29
 
22
30
  class Fault extends Error {
23
- constructor(readonly tag: string, message: string, readonly rpc = -32602) { super(message); }
31
+ constructor(readonly tag: string, message: string, readonly rpc = -32602, readonly expectedOffset?: number) { super(message); }
24
32
  }
25
33
  /** Thrown by a session factory to report a typed storage or lifecycle refusal. */
26
34
  export class SessionOpenError extends Error {
27
35
  constructor(readonly code: DurableErrorCode, message: string) { super(message); }
28
36
  }
29
- export interface SessionRequest { mode: "create" | "open"; sessionId: string; config?: ProtocolConfig;
37
+ export interface SessionRequest { mode: "create" | "open"; sessionId: string; config?: ProtocolConfig; mcpRuntimeHeaders?: unknown;
30
38
  /** Decision 0021: a catalog whose shape is valid. The factory checks its names
31
39
  * against its built-in tools and passes it to the session. */
32
40
  tools?: ToolCatalogInput }
@@ -39,6 +47,10 @@ export interface OpenedSession {
39
47
  commitConfig?(): void;
40
48
  /** One consistent logical copy, or `busy`. */
41
49
  exportArchive?(): StorageResult<SessionArchive>;
50
+ attachments?: ReturnType<typeof createManagedAttachmentService>;
51
+ imageInput?: boolean;
52
+ mcpStatus?(): Record<string, import("../../contracts/mcp.ts").McpServerStatus>;
53
+ stopMcp?(): Promise<void>;
42
54
  }
43
55
  export interface ProtocolServerOptions {
44
56
  durable?: boolean;
@@ -50,6 +62,9 @@ export interface ProtocolServerOptions {
50
62
  limits?: Partial<{ chunkBytes: number; maxBytes: number; idleMs: number }>;
51
63
  /** Decision 0021: the session factory accepts tool catalogs. */
52
64
  functions?: boolean;
65
+ attachments?: boolean;
66
+ mcpStdio?: boolean;
67
+ mcpHttps?: boolean;
53
68
  }
54
69
 
55
70
  const bad = (message: string): never => { throw new Fault("invalid_params", message); };
@@ -71,22 +86,24 @@ function count(value: unknown, fallback: number): number {
71
86
  }
72
87
  /** Capabilities describe this server instance: durable acceptance and load are
73
88
  * advertised only when its sessions are opened from durable storage. */
74
- export function describe(durable: boolean, archives = false, functions = false): Description {
89
+ export function describe(durable: boolean, archives = false, functions = false, attachments = false): Description {
75
90
  return {
91
+ ...(attachments ? { attachmentLimits: { fileBytes: ATTACHMENT_LIMITS.fileBytes, chunkBytes: ATTACHMENT_LIMITS.chunkBytes, openUploads: ATTACHMENT_LIMITS.openUploads, uploadIdleMs: ATTACHMENT_LIMITS.uploadIdleMs } } : {}),
76
92
  reminderLimits: { ...REMINDER_LIMITS, maxActiveRoutinesPerChannel: 20, maxRoutineCatchUp: 10 },
77
93
  configOptions: [], commands: [], policies: [],
78
- capabilities: { experimental: true, acceptance: durable ? "durable" : "memory", persistence: durable, startupChannelChanges: true, reminders: true, routines: true, unattendedTurnGuard: true, ...(functions ? { functions: true as const } : {}),
94
+ capabilities: { experimental: true, acceptance: durable ? "durable" : "memory", persistence: durable, startupChannelChanges: true, reminders: true, routines: true, unattendedTurnGuard: true, ...(functions ? { functions: true as const } : {}), ...(attachments ? { managedAttachments: true as const, orderedParts: true as const } : {}),
79
95
  methods: ["initialize", "config/validate", "session/create", ...(durable ? ["session/open"] : []), ...operatorMethods, "session/status", "reminder/change", "reminder/get", "reminder/list",
80
96
  "session/model-calls", "session/message/read", "session/suspend", "session/resume", "session/stop", "channel/push", "channel/notify", "channel/create", "channel/edit", "channel/suspend", "channel/resume", "channel/delete", "channel/withdraw", "channel/interrupt", "approval/respond", "session/idle",
81
- ...(archives ? ["session/export", "session/import", "transfer/open", "transfer/write", "transfer/read", "transfer/close"] : []), ...(functions ? toolMethods() : [])],
97
+ ...(archives ? ["session/export", "session/import", "transfer/open", "transfer/write", "transfer/read", "transfer/close"] : []), ...(functions ? toolMethods() : []), ...(attachments ? ["attachment/begin", "attachment/write", "attachment/status", "attachment/finalize", "attachment/abort", "attachment/read"] : [])],
82
98
  events: ["turn_started", "turn_took", "items_receipt", "text_delta", "text_gap", "text_incomplete", "tool_call", "message_completed", "turn_suspended", "turn_resumed", "turn_ended", "channel_state", "item_withdrawn", "approval_requested", "approval_closed", "reminder_changed", "reminder_fired", "reminder_expired", "reminder_cancelled", "routine_disposition", "routine_migration_blocked", "session/event"] },
83
99
  };
84
100
  }
85
101
 
86
- export function createProtocolServer(open: (request: SessionRequest) => Promise<OpenedSession>, options: ProtocolServerOptions = {}): ProtocolEndpoint & { dispose(): void } {
102
+ export function createProtocolServer(open: (request: SessionRequest) => Promise<OpenedSession>, options: ProtocolServerOptions = {}): ProtocolEndpoint & { dispose(): Promise<void> } {
87
103
  const limits = { ...TRANSFER_LIMITS, ...options.limits } as TransferLimits;
88
104
  const transfers = options.importArchive && options.transferDirectory ? createTransfers(options.transferDirectory, limits) : undefined;
89
- const description = describe(!!options.durable, !!transfers, !!options.functions);
105
+ const description = describe(!!options.durable, !!transfers, !!options.functions, !!options.attachments);
106
+ if (options.mcpStdio) description.capabilities.mcpServers = { stdio: true, http: !!options.mcpHttps, sse: false };
90
107
  let initialized = false;
91
108
  let approvalConsumer = false;
92
109
  let opening = false;
@@ -109,7 +126,11 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
109
126
  const catalogOf = (raw: unknown) => {
110
127
  if (raw === undefined) return undefined;
111
128
  if (!options.functions) bad("This server does not accept tool catalogs");
112
- try { return parseCatalog(raw, []); } catch (error) { throw error instanceof CatalogError ? new Fault(error.code, error.message) : error; }
129
+ try {
130
+ const parsed = parseCatalog(raw, []);
131
+ if (parsed.catalog.some(tool => tool.name.startsWith("mcp__"))) bad("MCP tool names are reserved");
132
+ return parsed;
133
+ } catch (error) { throw error instanceof CatalogError ? new Fault(error.code, error.message) : error; }
113
134
  };
114
135
 
115
136
  async function attach(request: SessionRequest): Promise<OpenedSession> {
@@ -162,9 +183,9 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
162
183
  }
163
184
  /** An open that fails after attaching releases the session. With a batch,
164
185
  * stop first: a resume in it may already have handed a turn to an executor. */
165
- function abandon(opened: OpenedSession, batch: boolean) {
186
+ async function abandon(opened: OpenedSession, batch: boolean) {
166
187
  if (batch) { try { opened.session.stop("Open failed"); } catch { /* Storage may be the failure. */ } }
167
- opened.close();
188
+ try { await opened.stopMcp?.(); } finally { opened.close(); }
168
189
  }
169
190
 
170
191
  /** Read one snapshot, then keep every later notification behind the response.
@@ -175,7 +196,10 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
175
196
  const reads = opened.session.operatorReads;
176
197
  if (!reads) throw new Fault("invalid_state", "Focused reads are unavailable");
177
198
  const { value, revision } = readValue(reads.readSession());
178
- return { sessionId: value.sessionId, lifecycle: value.lifecycle, revision };
199
+ const image = opened.imageInput && (opened.session.reminders?.executable() ?? true)
200
+ ? { imageInput: true as const, imageLimits: { formats: ["image/png", "image/jpeg", "image/webp"], fileBytes: ATTACHMENT_LIMITS.fileBytes,
201
+ turnBytes: ATTACHMENT_LIMITS.imageBytesPerTurn, maxImages: ATTACHMENT_LIMITS.references, maxSide: ATTACHMENT_LIMITS.imageSide, maxPixels: ATTACHMENT_LIMITS.imagePixels } } : {};
202
+ return { sessionId: value.sessionId, lifecycle: value.lifecycle, revision, ...image, ...(opened.mcpStatus ? { mcpServers: opened.mcpStatus() } : {}) };
179
203
  }
180
204
 
181
205
  function holdAfterResponse(start?: () => void) {
@@ -236,7 +260,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
236
260
  return { valid: true };
237
261
  }
238
262
  if (method === "session/create") {
239
- keys(p, ["sessionId", "config", "participants", "channels", "channelChanges", "tools", "reminderChanges"]);
263
+ keys(p, ["sessionId", "config", "participants", "channels", "channelChanges", "tools", "reminderChanges", "mcpRuntimeHeaders"]);
240
264
  const reminderBatch = parseReminderBatch(p.reminderChanges);
241
265
  const tools = catalogOf(p.tools);
242
266
  const sessionId = text(p.sessionId);
@@ -255,7 +279,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
255
279
  // effective configuration is known.
256
280
  const batch = p.channelChanges === undefined ? undefined : parseChannelChanges(p.channelChanges);
257
281
  if (batch && p.config?.policies) checkPolicies(batch, Object.keys(p.config.policies));
258
- const opened = await attach({ mode: "create", sessionId, config: p.config, ...(tools ? { tools } : {}) });
282
+ const opened = await attach({ mode: "create", sessionId, config: p.config, mcpRuntimeHeaders: p.mcpRuntimeHeaders, ...(tools ? { tools } : {}) });
259
283
  let results: ChannelChangeResult[] | undefined;
260
284
  let reminderResult: ReturnType<typeof reminderView>;
261
285
  try {
@@ -266,14 +290,14 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
266
290
  reminderResult = prepareReminders(opened.session, reminderBatch);
267
291
  current = opened;
268
292
  if (batch) startup = { batch, results: results! };
269
- } catch (error) { abandon(opened, !!batch); throw error; }
293
+ } catch (error) { try { await abandon(opened, !!batch); } catch { /* Preserve startup failure. */ } throw error; }
270
294
  finally { opening = false; }
271
295
  if (batch?.length || opened.session.reminders) holdAfterResponse(() => { if (current === opened) opened.session.start(); });
272
296
  else opened.session.start();
273
297
  return { ...(opened.session.operatorReads ? ready(opened) : { sessionId }), ...reminderResult, ...(results ? { channelChanges: results } : {}) };
274
298
  }
275
299
  if (method === "session/open") {
276
- keys(p, ["sessionId", "config", "channelChanges", "tools", "reminderChanges"]);
300
+ keys(p, ["sessionId", "config", "channelChanges", "tools", "reminderChanges", "mcpRuntimeHeaders"]);
277
301
  const reminderBatch = parseReminderBatch(p.reminderChanges);
278
302
  const tools = catalogOf(p.tools);
279
303
  const sessionId = text(p.sessionId);
@@ -282,13 +306,14 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
282
306
  // the batch was applied by the open and is only reported again. A new
283
307
  // batch belongs to the live channel API.
284
308
  if (current) {
309
+ if (p.mcpRuntimeHeaders !== undefined) bad("Runtime material requires a new executable open");
285
310
  if (ready(current).sessionId !== sessionId) throw new Fault("already_exists", "One session per endpoint");
286
311
  if (batch && !sameBatch(startup?.batch ?? [], batch)) throw new Fault("invalid_state", "The session is already open; send newer channel changes through the channel methods");
287
312
  if (tools && !(startupTools && sameCatalog(startupTools, tools))) throw new Fault("invalid_state", "The session is already open with another tool catalog; use the tool methods");
288
313
  if (p.reminderChanges !== undefined && JSON.stringify(reminderBatch) !== JSON.stringify(reminderStartup?.batch ?? [])) throw new Fault("invalid_state", "The session is already open; send changes through reminder/change");
289
314
  return { ...ready(current), ...reminderView(current.session, reminderStartup?.results), ...(startup ? { channelChanges: startup.results } : {}) };
290
315
  }
291
- const opened = await attach({ mode: "open", sessionId, config: p.config, ...(tools ? { tools } : {}) });
316
+ const opened = await attach({ mode: "open", sessionId, config: p.config, mcpRuntimeHeaders: p.mcpRuntimeHeaders, ...(tools ? { tools } : {}) });
292
317
  try {
293
318
  const finish = batch && await prepare(opened, batch);
294
319
  // From here to the end of the block nothing is awaited: the resumes, the
@@ -304,7 +329,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
304
329
  return { ...result, ...reminderResult, ...(results ? { channelChanges: results } : {}) };
305
330
  }
306
331
  // Work was not started; release the session so no partial load is observable.
307
- catch (error) { abandon(opened, !!batch); throw error; }
332
+ catch (error) { try { await abandon(opened, !!batch); } catch { /* Preserve startup failure. */ } throw error; }
308
333
  finally { opening = false; }
309
334
  }
310
335
  if (transfers && method.startsWith("transfer/")) {
@@ -323,7 +348,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
323
348
  else if (from.type === "transfer") { keys(from, ["type", "transferId"]); bytes = transfers.consume(from.transferId); }
324
349
  else return bad("Import source must be a path or a transfer");
325
350
  const payload = decodeArchive(bytes, limits.maxBytes) as SessionFilePayload<SessionArchive>;
326
- if (!payload || typeof payload !== "object" || Array.isArray(payload) || Object.keys(payload).sort().join() !== "archive,config" || ![2, 3, 4, 5, 6, 7].includes(payload.archive?.archiveVersion))
351
+ if (!payload || typeof payload !== "object" || Array.isArray(payload) || Object.keys(payload).sort().join() !== "archive,config" || ![2, 3, 4, 5, 6, 7, 8].includes(payload.archive?.archiveVersion))
327
352
  throw new Fault("invalid_archive", "Invalid session file payload");
328
353
  try { validateConfig(payload.config, (payload.archive as { archiveVersion: number }).archiveVersion === 2); } catch (error) { throw new Fault("invalid_archive", String(error)); }
329
354
  const sessionId = p.sessionId ?? payload.archive?.snapshot?.session?.sessionId;
@@ -352,6 +377,21 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
352
377
  milestone: result.milestone, ...(result.turnId === undefined ? {} : { turnId: String(result.turnId) }) } };
353
378
  }
354
379
  if (!current) throw new Fault("not_ready", "Create or load a session first");
380
+ if (method.startsWith("attachment/")) {
381
+ const service = current.attachments;
382
+ if (!service) throw new Fault("incompatible", "Managed attachments are unavailable");
383
+ const channel = text(p.channel);
384
+ if (method === "attachment/begin") {
385
+ keys(p, ["channel", "filename", "mediaType", "bytes", "sha256"]);
386
+ return service.begin({ channel, filename: p.filename, mediaType: text(p.mediaType), bytes: p.bytes, sha256: text(p.sha256) });
387
+ }
388
+ if (method === "attachment/read") { keys(p, ["channel", "id", "offset"]); return service.read(channel, text(p.id), p.offset); }
389
+ const uploadId = text(p.uploadId);
390
+ if (method === "attachment/status") { keys(p, ["channel", "uploadId"]); return service.status(channel, uploadId); }
391
+ if (method === "attachment/write") { keys(p, ["channel", "uploadId", "offset", "data"]); return service.write(channel, uploadId, p.offset, text(p.data)); }
392
+ if (method === "attachment/finalize") { keys(p, ["channel", "uploadId"]); return service.finalize(channel, uploadId); }
393
+ if (method === "attachment/abort") { keys(p, ["channel", "uploadId"]); service.abort(channel, uploadId); return {}; }
394
+ }
355
395
  if (transfers && method === "session/export") {
356
396
  keys(p, ["to"]);
357
397
  const to = obj(p.to);
@@ -416,7 +456,11 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
416
456
  return { channel: status, ...(method === "channel/create" ? { created: (result.value as { created: boolean }).created } : {}) };
417
457
  }
418
458
  if (method === "session/idle") { keys(p, []); return { idle: session.agent.idle() && session.status().execution !== "working" }; }
419
- if (method === "session/status") { keys(p, []); return wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()); }
459
+ if (method === "session/status") {
460
+ keys(p, []);
461
+ return { ...wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()),
462
+ ...(current.mcpStatus ? { mcpServers: current.mcpStatus() } : {}) };
463
+ }
420
464
  if (method === "session/suspend" || method === "session/resume") {
421
465
  keys(p, []);
422
466
  // Suspend answers only once `suspended` is committed, after in-flight
@@ -445,7 +489,12 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
445
489
  if (!session.reminders) throw new Fault("invalid_state", "Conditional stop is unavailable");
446
490
  return session.reminders.conditionalStop(windowMs);
447
491
  }
448
- if (method === "session/stop") { keys(p, []); return wireStatus(session.stop("Stopped by the host"), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()); }
492
+ if (method === "session/stop") {
493
+ keys(p, []);
494
+ const status = session.stop("Stopped by the host");
495
+ await current.stopMcp?.();
496
+ return wireStatus(status, session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot());
497
+ }
449
498
  if (method === "session/model-calls") {
450
499
  keys(p, ["after", "limit"]);
451
500
  const after = p.after === undefined ? undefined : text(p.after);
@@ -479,18 +528,21 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
479
528
  // One delivery behavior: the two legacy fields are checked, then ignored.
480
529
  if (item.kind !== "user_message" || (item.delivery !== undefined && item.delivery !== "queue") || (item.wake !== undefined && item.wake !== true)) bad("Only waking, queued user messages are supported");
481
530
  if (!Array.isArray(item.content) || !item.content.length) bad("Expected text parts");
482
- const parts = item.content.map((value: unknown) => { const part = obj(value); keys(part, ["type", "text"]);
483
- if (part.type !== "text") bad("Only text parts are supported"); return { type: "text", text: text(part.text) }; });
531
+ const mixed = item.content.some((value: unknown) => !!value && typeof value === "object" && (value as { type?: unknown }).type === "attachment");
532
+ const parts: InputPart[] = mixed ? validateMixedParts(item.content) : item.content.map((value: unknown) => { const part = obj(value); keys(part, ["type", "text"]);
533
+ if (part.type !== "text") bad("Only text parts are supported"); return { type: "text" as const, text: text(part.text) }; });
484
534
  // send returns once the item is committed to the inbox (Received) or
485
535
  // refused. It never waits for inference; the outcome arrives as events.
486
536
  const result = session.agent.send({ channelId: channel, participantId: sender, itemId: id, ...(item.policy == null ? {} : { policy: text(item.policy) }),
487
- text: parts.map((part: { text: string }) => part.text).join("\n") });
537
+ text: parts.flatMap(part => part.type === "text" ? [part.text] : []).join("\n"), ...(mixed ? { parts } : {}) });
488
538
  if (!result.accepted) throw new Fault(result.code === "invalid_input" ? "invalid_params" : result.code, result.error);
489
- const policy = session.operatorReads
490
- ? readValue(session.operatorReads.readTracked(channel, [id], [])).value.items[0]?.policy
491
- : session.snapshot().items.find(value => value.itemId === id)?.policy;
539
+ const saved = session.operatorReads
540
+ ? readValue(session.operatorReads.readTracked(channel, [id], [])).value.items[0]
541
+ : session.snapshot().items.find(value => value.itemId === id);
542
+ const policy = saved?.policy;
492
543
  return { accepted: true, duplicate: result.duplicate, item: { id, channel, kind: "participant_message", sender, milestone: result.milestone,
493
544
  ...(policy === undefined ? {} : { policy }),
545
+ ...(saved?.parts ? { parts: attachmentView(saved.parts, session.operatorReads?.readManagedAttachment, { ownerChannel: channel }) } : {}),
494
546
  ...(result.turnId === undefined ? {} : { turnId: String(result.turnId) }) } };
495
547
  }
496
548
  return {
@@ -502,10 +554,12 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
502
554
  return { jsonrpc: "2.0", id: request.id, result };
503
555
  } catch (error) {
504
556
  const fault = error instanceof FrameLimit ? new Fault("transfer_limit", error.message)
505
- : error instanceof ReminderShapeError ? new Fault("invalid_params", error.message)
557
+ : error instanceof ReminderShapeError || error instanceof AttachmentInputError ? new Fault(error instanceof AttachmentInputError ? error.code : "invalid_params", error.message)
558
+ : error instanceof UploadError ? new Fault(error.code, error.message, -32602, error.expectedOffset)
559
+ : error instanceof AttachmentReadError || error instanceof AttachmentServiceError ? new Fault(error.code, error.message)
506
560
  : error instanceof TransferFault || error instanceof SessionFileError || error instanceof OperatorFault || error instanceof ChannelChangeFault || error instanceof ToolFault ? new Fault(error.code, error.message) : error;
507
561
  return { jsonrpc: "2.0", id, error: { code: fault instanceof Fault ? fault.rpc : -32603,
508
- message: String(fault), data: { code: fault instanceof Fault ? fault.tag : "internal_error" } } };
562
+ message: String(fault), data: { code: fault instanceof Fault ? fault.tag : "internal_error", ...(fault instanceof Fault && fault.expectedOffset !== undefined ? { expectedOffset: fault.expectedOffset } : {}) } } };
509
563
  }
510
564
  },
511
565
  subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
@@ -514,6 +568,16 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
514
568
  respond(response) { bridge.respond(response); },
515
569
  // A connection that is gone serves no handler and answers no callback.
516
570
  disconnect() { approvalConsumer = false; current?.session.approvals.disconnect(); current?.session.tools?.serve([]); bridge.disconnect(); },
517
- dispose() { approvalConsumer = false; current?.session.approvals.disconnect(); bridge.disconnect(); transfers?.dispose(); current?.session.reminders?.releaseTimer(); current?.close(); current = undefined; },
571
+ async dispose() {
572
+ const opened = current;
573
+ current = undefined;
574
+ approvalConsumer = false;
575
+ opened?.session.approvals.disconnect();
576
+ bridge.disconnect();
577
+ transfers?.dispose();
578
+ opened?.session.reminders?.releaseTimer();
579
+ if (opened?.stopMcp) await opened.stopMcp();
580
+ opened?.close();
581
+ },
518
582
  };
519
583
  }
@@ -49,6 +49,7 @@ function message(value: any): value is RpcResponse | RpcNotification | RpcSessio
49
49
  && typeof event.toolCallId === "string" && typeof event.tool === "string" && typeof event.arguments === "string";
50
50
  case "turn_ended": return ["completed", "failed", "interrupted"].includes(event.outcome)
51
51
  && (event.error === undefined || typeof event.error === "string")
52
+ && (event.attachmentFailure === undefined || (["unsupported_image", "attachment_unavailable", "transfer_limit"].includes(event.attachmentFailure?.code) && strings(event.attachmentFailure?.attachmentIds)))
52
53
  && (event.uncertainCalls === undefined || strings(event.uncertainCalls));
53
54
  case "text_delta": return typeof event.messageId === "string" && typeof event.text === "string";
54
55
  case "text_gap": return typeof event.messageId === "string";
@@ -18,7 +18,8 @@
18
18
  .message.you { background: #253c5b; margin-left: 30px; } .message.error { border: 1px solid #c76464; }
19
19
  .message small { display: block; color: #a3b4d1; margin-bottom: 7px; }
20
20
  .message div { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.6; }
21
- #compose { padding: 12px 16px calc(12px + env(safe-area-inset-bottom)); border-top: 1px solid #30394b; }
21
+ #compose { padding: 12px 16px calc(12px + env(safe-area-inset-bottom)); border-top: 1px solid #30394b; flex-wrap: wrap; }
22
+ #files { width: auto; max-width: 100%; font-size: 13px; }
22
23
  textarea { resize: none; min-height: 48px; max-height: 180px; flex: 1; }
23
24
  #waiting { min-height: 20px; color: #a3b4d1; font-size: 13px; padding: 0 20px; }
24
25
  .spin { display: inline-block; width: 11px; height: 11px; border: 2px solid #4c6384; border-top-color: #a4c5ff; border-radius: 50%; animation: spin .8s linear infinite; margin-right: 7px; }
@@ -35,7 +36,7 @@
35
36
  </header>
36
37
  <main id="messages" role="log" aria-live="polite"></main>
37
38
  <div id="waiting" role="status"></div>
38
- <form id="compose"><textarea id="text" rows="2" placeholder="Message the agent…" aria-label="Message" disabled></textarea><button id="send" disabled>Send</button></form>
39
+ <form id="compose"><textarea id="text" rows="2" placeholder="Message the agent…" aria-label="Message" disabled></textarea><input id="files" type="file" multiple aria-label="Attach files" disabled><button id="send" disabled>Send</button></form>
39
40
  </div>
40
41
  <script>
41
42
  const $ = id => document.getElementById(id);
@@ -52,38 +53,90 @@
52
53
  const card = document.createElement('article'); card.className = 'message ' + type;
53
54
  const name = document.createElement('small'); name.textContent = label;
54
55
  const content = document.createElement('div'); content.textContent = text;
55
- card.append(name, content); $('messages').append(card); $('messages').scrollTop = $('messages').scrollHeight;
56
+ card.append(name, content); $('messages').append(card); $('messages').scrollTop = $('messages').scrollHeight; return card;
56
57
  }
57
58
  $('connect').onsubmit = event => {
58
59
  event.preventDefault(); source?.close(); generation++; pending = 0; waiting();
59
60
  channelId = $('channel').value.trim(); participantId = $('participant').value.trim();
60
61
  if (!channelId || !participantId) return;
61
- connected = false; $('send').disabled = $('text').disabled = true; $('messages').replaceChildren();
62
+ connected = false; $('send').disabled = $('text').disabled = $('files').disabled = true; $('messages').replaceChildren();
62
63
  status('Connecting…');
63
64
  source = new EventSource('/events?channelId=' + encodeURIComponent(channelId) + '&token=' + encodeURIComponent(token));
64
65
  source.addEventListener('ready', () => {
65
- connected = true; $('send').disabled = $('text').disabled = false;
66
+ connected = true; $('send').disabled = $('text').disabled = $('files').disabled = false;
66
67
  status('Connected · ' + channelId + ' · ' + participantId);
67
68
  });
68
69
  source.onmessage = event => { const output = JSON.parse(event.data); add('Agent', output.text, output.type === 'error' ? 'error' : ''); };
69
70
  source.onerror = () => {
70
- connected = false; $('send').disabled = $('text').disabled = true;
71
+ connected = false; $('send').disabled = $('text').disabled = $('files').disabled = true;
71
72
  source.close(); status('Connection lost. Use the startup pairing link and press Connect to reconnect.');
72
73
  };
73
74
  };
74
75
  const inputMaxBytes = __SESSION_INPUT_MAX_BYTES__;
76
+ async function post(path, body) {
77
+ const response = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token }, body: JSON.stringify(body) });
78
+ const result = await response.json().catch(() => ({}));
79
+ if (!response.ok) throw new Error(result.error || 'Request failed (' + response.status + ')');
80
+ return result;
81
+ }
82
+ // Web Crypto is unavailable on ordinary LAN HTTP; this bounded fallback keeps
83
+ // uploads usable on a paired device without sending unhashed bytes first.
84
+ function sha256Fallback(input) {
85
+ const k = [0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2];
86
+ const length = Math.ceil((input.length + 9) / 64) * 64, data = new Uint8Array(length); data.set(input); data[input.length] = 128;
87
+ const view = new DataView(data.buffer); view.setUint32(length - 8, Math.floor(input.length / 0x20000000)); view.setUint32(length - 4, input.length * 8);
88
+ const h = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19], w = new Uint32Array(64);
89
+ const r = (x, n) => (x >>> n) | (x << (32 - n));
90
+ for (let off = 0; off < length; off += 64) {
91
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + 4 * i);
92
+ for (let i = 16; i < 64; i++) { const a = w[i-15], b = w[i-2]; w[i] = (w[i-16] + (r(a,7)^r(a,18)^(a>>>3)) + w[i-7] + (r(b,17)^r(b,19)^(b>>>10))) >>> 0; }
93
+ let [a,b,c,d,e,f,g,z] = h;
94
+ for (let i = 0; i < 64; i++) { const t1 = (z+(r(e,6)^r(e,11)^r(e,25))+((e&f)^(~e&g))+k[i]+w[i])>>>0, t2 = ((r(a,2)^r(a,13)^r(a,22))+((a&b)^(a&c)^(b&c)))>>>0; z=g;g=f;f=e;e=(d+t1)>>>0;d=c;c=b;b=a;a=(t1+t2)>>>0; }
95
+ for (const [i, n] of [a,b,c,d,e,f,g,z].entries()) h[i] = (h[i] + n) >>> 0;
96
+ }
97
+ return h.map(n => n.toString(16).padStart(8, '0')).join('');
98
+ }
99
+ async function upload(file, channel) {
100
+ if (!file.size || file.size > 20 * 1024 * 1024) throw new Error('File must be between 1 byte and 20 MiB');
101
+ const bytes = new Uint8Array(await file.arrayBuffer());
102
+ const digest = globalThis.crypto?.subtle ? Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), n => n.toString(16).padStart(2, '0')).join('') : sha256Fallback(bytes);
103
+ const begun = await post('/attachments/begin', { channel, filename: file.name, mediaType: file.type || 'application/octet-stream', bytes: bytes.length, sha256: digest });
104
+ try {
105
+ for (let offset = 0; offset < bytes.length; offset += 384000) {
106
+ const chunk = bytes.subarray(offset, offset + 384000); let binary = '';
107
+ for (let i = 0; i < chunk.length; i += 8192) binary += String.fromCharCode(...chunk.subarray(i, i + 8192));
108
+ await post('/attachments/write', { channel, uploadId: begun.uploadId, offset, data: btoa(binary) });
109
+ }
110
+ return await post('/attachments/finalize', { channel, uploadId: begun.uploadId });
111
+ } catch (error) { await post('/attachments/abort', { channel, uploadId: begun.uploadId }).catch(() => {}); throw error; }
112
+ }
113
+ function attachDownload(card, channel, metadata) {
114
+ const button = document.createElement('button'); button.type = 'button'; button.textContent = 'Download ' + metadata.filename;
115
+ button.onclick = async () => {
116
+ button.disabled = true;
117
+ try {
118
+ const chunks = []; let offset = 0;
119
+ do { const page = await post('/attachments/read', { channel, id: metadata.id, offset }); const raw = atob(page.data), bytes = new Uint8Array(raw.length); for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i); chunks.push(bytes); offset = page.nextOffset ?? -1; } while (offset >= 0);
120
+ const url = URL.createObjectURL(new Blob(chunks, { type: metadata.mediaType })), link = document.createElement('a'); link.href = url; link.download = metadata.filename; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
121
+ } catch (error) { add('Error', String(error), 'error'); } finally { button.disabled = false; }
122
+ };
123
+ card.append(button);
124
+ }
75
125
  $('compose').onsubmit = async event => {
76
- event.preventDefault(); const text = $('text').value.trim();
77
- if (!connected || !text) return;
126
+ event.preventDefault(); const text = $('text').value.trim(), files = [...$('files').files];
127
+ if (!connected || (!text && !files.length)) return;
128
+ if (files.length > 8) { add('Error', 'Attach at most 8 files', 'error'); return; }
78
129
  if (new TextEncoder().encode(text).length > inputMaxBytes) {
79
130
  add('Error', 'Input exceeds the ' + inputMaxBytes + '-byte UTF-8 limit', 'error');
80
131
  return;
81
132
  }
82
- const submittedGeneration = generation;
83
- add(participantId, text, 'you'); $('text').value = ''; pending++; waiting();
133
+ const submittedGeneration = generation, channel = channelId, participant = participantId;
134
+ $('text').value = ''; $('files').value = ''; pending++; waiting();
84
135
  try {
85
- const response = await fetch('/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token }, body: JSON.stringify({channelId, participantId, text}) });
86
- if (!response.ok) throw new Error((await response.json().catch(() => null))?.error || 'Request failed (' + response.status + ')');
136
+ const uploaded = []; for (const file of files) uploaded.push(await upload(file, channel));
137
+ const parts = [...(text ? [{ type: 'text', text }] : []), ...uploaded.map(metadata => ({ type: 'attachment', id: metadata.id }))];
138
+ const card = add(participant, text || 'Attachment', 'you'); for (const metadata of uploaded) attachDownload(card, channel, metadata);
139
+ await post('/messages', { channelId: channel, participantId: participant, text, ...(uploaded.length ? { parts } : {}) });
87
140
  // The answer arrives on SSE; printing this HTTP response would duplicate it.
88
141
  } catch (error) { if (generation === submittedGeneration) add('Error', String(error), 'error'); }
89
142
  finally { if (generation === submittedGeneration) { pending--; waiting(); } }
@@ -1,13 +1,15 @@
1
1
  import { SESSION_INPUT_MAX_BYTES } from "../../contracts/input-limits.ts";
2
2
  import { networkInterfaces } from "node:os";
3
+ import type { createManagedAttachmentService } from "../../capabilities/attachments/service.ts";
3
4
 
4
5
  /** Separate LAN surface; the inspector remains bound to loopback. */
5
- export function serveWebChat(handleChannel: (request: Request) => Promise<Response>, port = 3001, token: string = crypto.randomUUID()) {
6
+ export function serveWebChat(handleChannel: (request: Request) => Promise<Response>, port = 3001, token: string = crypto.randomUUID(),
7
+ options: { attachments?: ReturnType<typeof createManagedAttachmentService>; ensureChannel?: (id: string) => void } = {}) {
6
8
  const page = Bun.file(new URL("./index.html", import.meta.url)).text().then(
7
9
  html => html.replace("__SESSION_INPUT_MAX_BYTES__", String(SESSION_INPUT_MAX_BYTES)),
8
10
  );
9
11
  const server = Bun.serve({
10
- hostname: "0.0.0.0", port, development: false, idleTimeout: 0,
12
+ hostname: "0.0.0.0", port, development: false, idleTimeout: 0, maxRequestBodySize: 1024 * 1024,
11
13
  async fetch(request) {
12
14
  const url = new URL(request.url);
13
15
  if (url.pathname === "/" && request.method === "GET") {
@@ -15,11 +17,36 @@ export function serveWebChat(handleChannel: (request: Request) => Promise<Respon
15
17
  "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
16
18
  } });
17
19
  }
18
- if (url.pathname !== "/messages" && url.pathname !== "/events") return new Response("Not found", { status: 404 });
20
+ if (url.pathname !== "/messages" && url.pathname !== "/events" && !url.pathname.startsWith("/attachments/")) return new Response("Not found", { status: 404 });
19
21
  const supplied = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? url.searchParams.get("token");
20
22
  if (supplied !== token) return new Response("Open the pairing link printed by the agent", { status: 401 });
21
23
  const origin = request.headers.get("origin");
22
24
  if (origin && origin !== url.origin) return new Response("Invalid origin", { status: 403 });
25
+ if (url.pathname.startsWith("/attachments/")) {
26
+ const service = options.attachments;
27
+ if (!service) return Response.json({ error: "Attachments are unavailable", code: "incompatible" }, { status: 404 });
28
+ if (request.method !== "POST") return new Response("Use POST", { status: 405 });
29
+ try {
30
+ const body = await request.json() as Record<string, unknown>;
31
+ if (!body || typeof body !== "object" || Array.isArray(body) || typeof body.channel !== "string" || !body.channel.trim()) throw new Error("Invalid attachment request");
32
+ const channel = body.channel;
33
+ const exact = (keys: string[]) => { if (Object.keys(body).some(key => !keys.includes(key))) throw new Error("Invalid attachment field"); };
34
+ if (url.pathname === "/attachments/begin") {
35
+ exact(["channel", "filename", "mediaType", "bytes", "sha256"]); options.ensureChannel?.(channel);
36
+ return Response.json(service.begin({ channel, filename: body.filename as string, mediaType: body.mediaType as string, bytes: body.bytes as number, sha256: body.sha256 as string }));
37
+ }
38
+ if (url.pathname === "/attachments/read") { exact(["channel", "id", "offset"]); return Response.json(service.read(channel, body.id as string, body.offset as number)); }
39
+ if (typeof body.uploadId !== "string" || !body.uploadId) throw new Error("Invalid upload ID");
40
+ if (url.pathname === "/attachments/status") { exact(["channel", "uploadId"]); return Response.json(service.status(channel, body.uploadId)); }
41
+ if (url.pathname === "/attachments/write") { exact(["channel", "uploadId", "offset", "data"]); return Response.json(service.write(channel, body.uploadId, body.offset as number, body.data as string)); }
42
+ if (url.pathname === "/attachments/finalize") { exact(["channel", "uploadId"]); return Response.json(await service.finalize(channel, body.uploadId)); }
43
+ if (url.pathname === "/attachments/abort") { exact(["channel", "uploadId"]); service.abort(channel, body.uploadId); return Response.json({}); }
44
+ return new Response("Not found", { status: 404 });
45
+ } catch (error) {
46
+ const fault = error as { code?: string; message?: string; expectedOffset?: number };
47
+ return Response.json({ error: fault.message ?? String(error), code: fault.code ?? "invalid_params", ...(fault.expectedOffset === undefined ? {} : { expectedOffset: fault.expectedOffset }) }, { status: fault.code === "not_found" ? 404 : 400 });
48
+ }
49
+ }
23
50
  return handleChannel(request);
24
51
  },
25
52
  });