dsh-codex-subscription 3.1.5 → 3.1.6

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.
package/lib/index.js CHANGED
@@ -20,6 +20,7 @@ import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } fr
20
20
  import { defineTool } from "@deepseek-ai/dsh-tools";
21
21
  import * as dshCredentials from "@deepseek-ai/dsh-credentials";
22
22
  import { homedir, hostname } from "node:os";
23
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
23
24
  import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
24
25
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
25
26
  import { WebError } from "@deepseek-ai/dsh-web";
@@ -792,8 +793,8 @@ const LEVELS$1 = [
792
793
  "warn",
793
794
  "error"
794
795
  ];
795
- const MAX_ENTRIES$1 = 400;
796
- const FILE_LIMIT = 256 * 1024;
796
+ const MAX_ENTRIES$1 = 1e3;
797
+ const FILE_LIMIT = 1024 * 1024;
797
798
  function createDiagnosticLog({ now = Date.now, limit = MAX_ENTRIES$1 } = {}) {
798
799
  let entries = [];
799
800
  let dropped = 0;
@@ -1250,9 +1251,9 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
1250
1251
  //#region src/subscription-compaction.js
1251
1252
  /** Experimental SSE bridge; callers must explicitly opt in. */
1252
1253
  const clone$2 = (value) => JSON.parse(JSON.stringify(value));
1253
- const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1254
+ const hash$1 = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1254
1255
  const key = "codexCompactionV1";
1255
- const historyHash = (messages) => hash(messages.map(({ source, ...message }) => ({
1256
+ const historyHash = (messages) => hash$1(messages.map(({ source, ...message }) => ({
1256
1257
  ...message,
1257
1258
  source: source && {
1258
1259
  kind: source.kind,
@@ -1277,7 +1278,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1277
1278
  const identity = await accountScope(options);
1278
1279
  if (!identity) throw new Error("Compaction requires a stable account identity");
1279
1280
  const state = {
1280
- identity: hash([identity, options.model]),
1281
+ identity: hash$1([identity, options.model]),
1281
1282
  original: options.messages,
1282
1283
  blocks: [],
1283
1284
  suffix: void 0,
@@ -1287,7 +1288,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1287
1288
  for (let i = messages.length - 1; i >= 0; i--) {
1288
1289
  const candidate = messages[i].source?.replayState?.response?.[key];
1289
1290
  if (!candidate) continue;
1290
- if (Number.isFinite(candidate.createdAt) && candidate.createdAt <= now() && now() - candidate.createdAt <= MAX_AGE_MS && candidate.scope === state.identity && candidate.prefix === historyHash(messages.slice(0, i)) && candidate.content === hash(messages[i].content) && Array.isArray(candidate.items) && candidate.items[0]?.type === "compaction" && typeof candidate.items[0].encrypted_content === "string" && candidate.digest === hash(candidate.items) && JSON.stringify(candidate.items).length <= MAX_BYTES) {
1291
+ if (Number.isFinite(candidate.createdAt) && candidate.createdAt <= now() && now() - candidate.createdAt <= MAX_AGE_MS && candidate.scope === state.identity && candidate.prefix === historyHash(messages.slice(0, i)) && candidate.content === hash$1(messages[i].content) && Array.isArray(candidate.items) && candidate.items[0]?.type === "compaction" && typeof candidate.items[0].encrypted_content === "string" && candidate.digest === hash$1(candidate.items) && JSON.stringify(candidate.items).length <= MAX_BYTES) {
1291
1292
  state.suffix = clone$2(candidate.items);
1292
1293
  messages = [...messages.slice(0, i + 1).filter((m) => m.role === "system"), ...messages.slice(i + 1)];
1293
1294
  }
@@ -1314,9 +1315,9 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1314
1315
  createdAt: now(),
1315
1316
  scope: state.identity,
1316
1317
  prefix: historyHash(state.original),
1317
- content: hash(state.blocks.filter(Boolean)),
1318
+ content: hash$1(state.blocks.filter(Boolean)),
1318
1319
  items,
1319
- digest: hash(items)
1320
+ digest: hash$1(items)
1320
1321
  };
1321
1322
  event = {
1322
1323
  ...event,
@@ -2021,7 +2022,7 @@ const REASONING_LIMITS = Object.freeze({
2021
2022
  bytes: 16 * 1024 * 1024,
2022
2023
  updates: 128
2023
2024
  });
2024
- const record$9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2025
+ const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2025
2026
  const efforts = /* @__PURE__ */ new Set([
2026
2027
  "low",
2027
2028
  "medium",
@@ -2035,13 +2036,13 @@ const reasoningDigest = (value) => {
2035
2036
  const text = boundedStringify(value, REASONING_LIMITS.bytes);
2036
2037
  return text === void 0 ? void 0 : reasoningHash(text);
2037
2038
  };
2038
- const boundary = (value, update = false) => record$9(value) && Object.keys(value).every((key) => [
2039
+ const boundary = (value, update = false) => record$8(value) && Object.keys(value).every((key) => [
2039
2040
  "offset",
2040
2041
  "hash",
2041
2042
  ...update ? ["effort"] : []
2042
2043
  ].includes(key)) && Number.isInteger(value.offset) && value.offset >= 0 && value.offset <= REASONING_LIMITS.items && isHash(value.hash);
2043
2044
  function isReasoningState(value) {
2044
- if (!record$9(value) || value.version !== 1 || !isHash(value.scope) || !isHash(value.envelope) || !efforts.has(value.baseline) || !boundary(value.last) || !Array.isArray(value.updates) || value.updates.length > REASONING_LIMITS.updates || Object.keys(value).some((key) => ![
2045
+ if (!record$8(value) || value.version !== 1 || !isHash(value.scope) || !isHash(value.envelope) || !efforts.has(value.baseline) || !boundary(value.last) || !Array.isArray(value.updates) || value.updates.length > REASONING_LIMITS.updates || Object.keys(value).some((key) => ![
2045
2046
  "version",
2046
2047
  "scope",
2047
2048
  "envelope",
@@ -2075,7 +2076,7 @@ function rewriteReasoning(payload, { model, scope, previous, fresh = false }) {
2075
2076
  payload,
2076
2077
  reason
2077
2078
  });
2078
- if (!supportsReasoningUpdates(model) || !record$9(payload) || payload.model !== model.id || !Array.isArray(payload.input) || !record$9(payload.reasoning) || !efforts.has(payload.reasoning.effort)) return skip("unsupported-request");
2079
+ if (!supportsReasoningUpdates(model) || !record$8(payload) || payload.model !== model.id || !Array.isArray(payload.input) || !record$8(payload.reasoning) || !efforts.has(payload.reasoning.effort)) return skip("unsupported-request");
2079
2080
  if (payload.context_management !== void 0) return skip("cloud-compaction");
2080
2081
  if (payload.multi_agent !== void 0 || payload.reasoning.mode !== void 0 && payload.reasoning.mode !== "standard" || payload.previous_response_id !== void 0 || payload.conversation !== void 0 || payload.background === true || payload.truncation !== void 0 && payload.truncation !== "disabled" || payload.input.some((item) => [
2081
2082
  "configuration_update",
@@ -3391,7 +3392,7 @@ function inheritedOriginalImageRef(session, assetId) {
3391
3392
  }
3392
3393
  //#endregion
3393
3394
  //#region src/version.js
3394
- const PACKAGE_VERSION = "3.1.5";
3395
+ const PACKAGE_VERSION = "3.1.6";
3395
3396
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3396
3397
  //#endregion
3397
3398
  //#region src/codex-images.js
@@ -3419,7 +3420,7 @@ const FULL_ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/u;
3419
3420
  const BARE_ATTACHMENT_DIGEST = /^[0-9a-f]{64}$/iu;
3420
3421
  const PATH_LIKE_ATTACHMENT_ID = /[\\/]/u;
3421
3422
  const FILE_NAME_ATTACHMENT_ID = /\.[A-Za-z0-9]{1,16}$/u;
3422
- const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3423
+ const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3423
3424
  const nonEmpty$2 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
3424
3425
  const NETWORK_REASONS = {
3425
3426
  UND_ERR_HEADERS_TIMEOUT: "the image service sent no response within 5 minutes",
@@ -3505,7 +3506,7 @@ function decodeCodexPng(value, maximumBytes) {
3505
3506
  return new Uint8Array(data);
3506
3507
  }
3507
3508
  function imageReference(value) {
3508
- const originalDimensions = record$8(value.originalDimensions) ? {
3509
+ const originalDimensions = record$7(value.originalDimensions) ? {
3509
3510
  width: value.originalDimensions.width,
3510
3511
  height: value.originalDimensions.height
3511
3512
  } : void 0;
@@ -3533,7 +3534,7 @@ function invalidAttachmentId(value) {
3533
3534
  function referenceOf(value, attachments) {
3534
3535
  const attachmentId = normalizeAttachmentId(value?.attachmentId);
3535
3536
  if (attachmentId === void 0) invalidAttachmentId(value);
3536
- if (!record$8(value) || !attachments.imageLimits.mediaTypes.includes(value.mediaType) || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 || !Number.isSafeInteger(value.width) || value.width <= 0 || !Number.isSafeInteger(value.height) || value.height <= 0 || value.name !== void 0 && (typeof value.name !== "string" || value.name.length > 256) || value.originalDimensions !== void 0 && (!record$8(value.originalDimensions) || !Number.isSafeInteger(value.originalDimensions.width) || value.originalDimensions.width <= 0 || !Number.isSafeInteger(value.originalDimensions.height) || value.originalDimensions.height <= 0)) throw new Error("referenceImages contains an invalid image reference");
3537
+ if (!record$7(value) || !attachments.imageLimits.mediaTypes.includes(value.mediaType) || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 || !Number.isSafeInteger(value.width) || value.width <= 0 || !Number.isSafeInteger(value.height) || value.height <= 0 || value.name !== void 0 && (typeof value.name !== "string" || value.name.length > 256) || value.originalDimensions !== void 0 && (!record$7(value.originalDimensions) || !Number.isSafeInteger(value.originalDimensions.width) || value.originalDimensions.width <= 0 || !Number.isSafeInteger(value.originalDimensions.height) || value.originalDimensions.height <= 0)) throw new Error("referenceImages contains an invalid image reference");
3537
3538
  return imageReference({
3538
3539
  ...value,
3539
3540
  attachmentId
@@ -3543,7 +3544,7 @@ function sessionImageReferences(messages) {
3543
3544
  const references = /* @__PURE__ */ new Map();
3544
3545
  const visit = (content) => {
3545
3546
  if (!Array.isArray(content)) return;
3546
- for (const block of content) if (block?.type === "image" && record$8(block.attachment)) {
3547
+ for (const block of content) if (block?.type === "image" && record$7(block.attachment)) {
3547
3548
  const id = normalizeAttachmentId(block.attachment.attachmentId);
3548
3549
  if (id !== void 0) references.set(id, block.attachment);
3549
3550
  } else if (block?.type === "tool-result") visit(block.content);
@@ -3708,7 +3709,7 @@ async function limitMessage(response, now = Date.now()) {
3708
3709
  } catch {
3709
3710
  return fallback;
3710
3711
  }
3711
- if (!record$8(error)) return fallback;
3712
+ if (!record$7(error)) return fallback;
3712
3713
  const at = Number.isSafeInteger(error.resets_at) && error.resets_at > 0 ? error.resets_at * 1e3 : Number.isSafeInteger(error.resets_in_seconds) && error.resets_in_seconds > 0 ? now + error.resets_in_seconds * 1e3 : void 0;
3713
3714
  if (at === void 0) return fallback;
3714
3715
  const minutes = Math.max(1, Math.ceil((at - now) / 6e4));
@@ -3720,7 +3721,7 @@ async function refusalMessage(response, editing) {
3720
3721
  let reason;
3721
3722
  try {
3722
3723
  const value = JSON.parse(await readTextWithin(response, 16 * 1024));
3723
- const error = record$8(value?.error) ? value.error : void 0;
3724
+ const error = record$7(value?.error) ? value.error : void 0;
3724
3725
  reason = [
3725
3726
  error?.message,
3726
3727
  value?.detail,
@@ -3745,7 +3746,7 @@ async function readTextWithin(response, maximumBytes) {
3745
3746
  }
3746
3747
  function responseMetadata(value) {
3747
3748
  const data = Array.isArray(value?.data) ? value.data[0] : void 0;
3748
- const encoded = record$8(data) ? data.b64_json : void 0;
3749
+ const encoded = record$7(data) ? data.b64_json : void 0;
3749
3750
  if (typeof encoded !== "string") throw new Error("Codex returned no image data");
3750
3751
  return {
3751
3752
  encoded,
@@ -4198,6 +4199,48 @@ function createSketchAgentTool(bridge, attachments, getSessionMessages = () => [
4198
4199
  });
4199
4200
  }
4200
4201
  //#endregion
4202
+ //#region src/remote-control-log.js
4203
+ const IDS = /* @__PURE__ */ new Set([
4204
+ "requestId",
4205
+ "clientId",
4206
+ "threadId",
4207
+ "turnId",
4208
+ "itemId",
4209
+ "attachmentId"
4210
+ ]);
4211
+ const FIELDS = /* @__PURE__ */ new Set([
4212
+ "method",
4213
+ "status",
4214
+ "type",
4215
+ "code",
4216
+ "ms",
4217
+ "bytes",
4218
+ "items",
4219
+ "turns",
4220
+ "images",
4221
+ "segments",
4222
+ "sequence",
4223
+ "chunks",
4224
+ "hasClientId",
4225
+ "matched",
4226
+ "pending",
4227
+ "event",
4228
+ "error"
4229
+ ]);
4230
+ function phoneLog(event, details = {}, level = "info") {
4231
+ const fields = {};
4232
+ for (const [name, value] of Object.entries(details)) {
4233
+ if (value === void 0 || value === null) continue;
4234
+ if (IDS.has(name)) fields[name] = createHash("sha256").update(String(value)).digest("hex").slice(0, 12);
4235
+ else if (FIELDS.has(name) && [
4236
+ "string",
4237
+ "number",
4238
+ "boolean"
4239
+ ].includes(typeof value)) fields[name] = value;
4240
+ }
4241
+ diagnosticLog.log(level, "phone", event, JSON.stringify(fields));
4242
+ }
4243
+ //#endregion
4201
4244
  //#region src/remote-control-host.js
4202
4245
  const METHOD_NOT_FOUND = -32601;
4203
4246
  const INVALID_PARAMS = -32602;
@@ -4231,7 +4274,7 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4231
4274
  if (!debug) return;
4232
4275
  const value = {
4233
4276
  at: Date.now(),
4234
- ...entry
4277
+ ...Object.fromEntries(Object.entries(entry).map(([key, value]) => [key, typeof value === "string" ? value.replace(/https?:\/\/[^\s"'<>]+/gu, (url) => url.split(/[?#]/u)[0]) : value]))
4235
4278
  };
4236
4279
  trace.push(value);
4237
4280
  if (trace.length > 60) trace.shift();
@@ -4266,10 +4309,28 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4266
4309
  message: params?.message
4267
4310
  })
4268
4311
  });
4269
- await client.send(params === void 0 ? { method } : {
4270
- method,
4271
- params
4272
- });
4312
+ try {
4313
+ await client.send(params === void 0 ? { method } : {
4314
+ method,
4315
+ params
4316
+ });
4317
+ if (!STREAMING.test(method)) phoneLog("notification sent", {
4318
+ method,
4319
+ clientId: client.id,
4320
+ threadId: params?.threadId,
4321
+ turnId: params?.turnId,
4322
+ itemId: params?.item?.id,
4323
+ type: params?.item?.type
4324
+ });
4325
+ } catch (error) {
4326
+ phoneLog("notification failed", {
4327
+ method,
4328
+ clientId: client.id,
4329
+ threadId: params?.threadId,
4330
+ error: error?.message
4331
+ }, "error");
4332
+ throw error;
4333
+ }
4273
4334
  };
4274
4335
  /** Ask the phone something (approvals); settles with its result or rejects. */
4275
4336
  const ask = (method, params, signal) => new Promise((resolve, reject) => {
@@ -4359,6 +4420,17 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4359
4420
  return;
4360
4421
  }
4361
4422
  note("request", method);
4423
+ const started = Date.now();
4424
+ const logged = {
4425
+ method,
4426
+ requestId: id,
4427
+ clientId: client.id,
4428
+ threadId: params?.threadId
4429
+ };
4430
+ phoneLog("request received", {
4431
+ ...logged,
4432
+ hasClientId: typeof params?.clientUserMessageId === "string"
4433
+ });
4362
4434
  if (!active && method !== "initialize") {
4363
4435
  active = true;
4364
4436
  onActive?.(client, notify);
@@ -4369,6 +4441,10 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4369
4441
  });
4370
4442
  const handler = methods[method];
4371
4443
  if (!handler) {
4444
+ phoneLog("method unavailable", {
4445
+ ...logged,
4446
+ code: METHOD_NOT_FOUND
4447
+ }, "warn");
4372
4448
  record({
4373
4449
  method,
4374
4450
  missing: true,
@@ -4383,16 +4459,40 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4383
4459
  Promise.resolve().then(() => handler(params, {
4384
4460
  ...context,
4385
4461
  signal: controller.signal
4386
- })).then((result) => reply(id, result ?? {}), (error) => {
4462
+ })).then(async (result) => {
4463
+ await reply(id, result ?? {});
4464
+ phoneLog("request completed", {
4465
+ ...logged,
4466
+ ms: Date.now() - started,
4467
+ bytes: Buffer.byteLength(JSON.stringify(result ?? {})),
4468
+ turns: result?.thread?.turns?.length
4469
+ });
4470
+ }, (error) => {
4471
+ phoneLog("request failed", {
4472
+ ...logged,
4473
+ ms: Date.now() - started,
4474
+ code: error?.code,
4475
+ error: error?.message
4476
+ }, "error");
4387
4477
  if (!QUIET$1.has(method)) record({
4388
4478
  method,
4389
4479
  error: String(error?.message ?? error).slice(0, 300),
4390
4480
  params: JSON.stringify(params ?? null).slice(0, 600)
4391
4481
  });
4392
4482
  return fail(id, error);
4393
- }).catch(() => {}).finally(() => aborts.delete(controller));
4483
+ }).catch((error) => {
4484
+ phoneLog("response failed", {
4485
+ ...logged,
4486
+ ms: Date.now() - started,
4487
+ error: error?.message
4488
+ }, "error");
4489
+ }).finally(() => aborts.delete(controller));
4394
4490
  },
4395
4491
  close() {
4492
+ phoneLog("client disconnected", {
4493
+ clientId: client.id,
4494
+ pending: aborts.size
4495
+ });
4396
4496
  for (const waiting of [...pending.values()]) waiting.reject(new RpcError(-32800, "Client disconnected"));
4397
4497
  for (const controller of aborts) controller.abort();
4398
4498
  aborts.clear();
@@ -4678,6 +4778,15 @@ function createRemoteControlRelay(options) {
4678
4778
  if (bytes.byteLength > MAX_MESSAGE_BYTES) throw new RemoteControlError("too-large", "Remote Control message is too large");
4679
4779
  const chunks = [];
4680
4780
  for (let offset = 0; offset < bytes.byteLength; offset += TARGET_SEGMENT_BYTES) chunks.push(bytes.subarray(offset, offset + TARGET_SEGMENT_BYTES).toString("base64"));
4781
+ const started = now();
4782
+ phoneLog("chunked send started", {
4783
+ clientId,
4784
+ method: message.method,
4785
+ requestId: message.id,
4786
+ bytes: bytes.byteLength,
4787
+ segments: chunks.length,
4788
+ sequence
4789
+ });
4681
4790
  for (const [segmentId, chunk] of chunks.entries()) {
4682
4791
  const text = JSON.stringify({
4683
4792
  client_id: clientId,
@@ -4695,6 +4804,13 @@ function createRemoteControlRelay(options) {
4695
4804
  if (socket?.readyState === 1) await new Promise((resolve) => socket.send(text, () => resolve()));
4696
4805
  }
4697
4806
  }
4807
+ phoneLog("chunked send completed", {
4808
+ clientId,
4809
+ bytes: bytes.byteLength,
4810
+ segments: chunks.length,
4811
+ sequence,
4812
+ ms: now() - started
4813
+ });
4698
4814
  };
4699
4815
  const closeClient = (clientId, streamId) => {
4700
4816
  for (const [key, client] of clients) if (key.startsWith(`${clientId}\u0000`) && (streamId === void 0 || key === `${clientId}\u0000${streamId}`)) {
@@ -4729,12 +4845,18 @@ function createRemoteControlRelay(options) {
4729
4845
  if (!client && !starts) return;
4730
4846
  if (!client) {
4731
4847
  let closed = false;
4848
+ let sending = Promise.resolve();
4732
4849
  const connection = options.serve({
4733
4850
  id: `${envelope.client_id}/${streamId}`,
4734
4851
  clientId: envelope.client_id,
4735
4852
  streamId,
4736
- send: async (message) => {
4737
- if (!closed) await sendServerMessage(envelope.client_id, streamId, message);
4853
+ send: (message) => {
4854
+ const snapshot = structuredClone(message);
4855
+ const next = sending.then(() => {
4856
+ if (!closed) return sendServerMessage(envelope.client_id, streamId, snapshot);
4857
+ });
4858
+ sending = next.catch(() => {});
4859
+ return next;
4738
4860
  },
4739
4861
  close: () => {
4740
4862
  closed = true;
@@ -4749,6 +4871,7 @@ function createRemoteControlRelay(options) {
4749
4871
  }
4750
4872
  };
4751
4873
  clients.set(key, client);
4874
+ phoneLog("client stream opened", { clientId: envelope.client_id });
4752
4875
  }
4753
4876
  if (!(!starts && Number.isInteger(envelope.seq_id) && (lastInbound.get(key) ?? -1) >= envelope.seq_id)) {
4754
4877
  if (Number.isInteger(envelope.seq_id)) lastInbound.set(key, envelope.seq_id);
@@ -4879,6 +5002,10 @@ function createRemoteControlRelay(options) {
4879
5002
  ws.on("message", (data) => {
4880
5003
  queue = queue.then(() => receive(String(data))).catch((error) => {
4881
5004
  state.lastError = error?.code ?? "protocol";
5005
+ phoneLog("relay message failed", {
5006
+ code: error?.code,
5007
+ error: error?.message
5008
+ }, "error");
4882
5009
  });
4883
5010
  });
4884
5011
  ws.on("error", (error) => {
@@ -6255,6 +6382,81 @@ function createRealtimeVoice(options) {
6255
6382
  };
6256
6383
  }
6257
6384
  //#endregion
6385
+ //#region src/remote-control-image-output.js
6386
+ const images = /* @__PURE__ */ new WeakMap();
6387
+ const renderedSources = /* @__PURE__ */ new WeakMap();
6388
+ const metadata = (message) => {
6389
+ for (const block of message.content ?? []) if (block.type === "text") try {
6390
+ const value = JSON.parse(block.text);
6391
+ if (value && typeof value === "object") return value;
6392
+ } catch {}
6393
+ };
6394
+ function rememberRemoteImage(item, message, assets) {
6395
+ const image = (message.content ?? []).find((block) => block.type === "image" && assets.has(block.attachment?.attachmentId));
6396
+ images.set(item, {
6397
+ asset: image ? assets.get(image.attachment.attachmentId) : void 0,
6398
+ state: metadata(message)
6399
+ });
6400
+ }
6401
+ const pathKey = (value) => typeof value === "string" ? value.replaceAll("\\", "/").replace(/^\.\//u, "") : "";
6402
+ const filename = (value) => pathKey(value).split("/").at(-1);
6403
+ const matchesPresentedPath = (path, ref) => {
6404
+ const normal = (value) => /^[A-Za-z]:\//u.test(pathKey(path)) ? pathKey(value).toLowerCase() : pathKey(value);
6405
+ return normal(path) === normal(ref) || !/[\\/]/u.test(ref) && normal(filename(path)) === normal(filename(ref));
6406
+ };
6407
+ const fullPreview = (item) => item.arguments?.action === "preview" && !item.arguments?.box && (!item.arguments?.mode || item.arguments.mode === "full");
6408
+ /** A native image or the exact full preview of a successfully finished sketch. */
6409
+ function withRemoteImageOutput(turn) {
6410
+ const previews = /* @__PURE__ */ new Map(), outputs = [], sketchOutputs = /* @__PURE__ */ new Set();
6411
+ let lastOutput = -1;
6412
+ for (const [index, item] of turn.items.entries()) {
6413
+ const record = images.get(item);
6414
+ if (item.status !== "completed" || !record) continue;
6415
+ let asset;
6416
+ if (item.type === "imageGeneration") asset = record.asset;
6417
+ else if (item.type === "dynamicToolCall" && item.tool === "codex_sketch" && item.success) {
6418
+ const state = record.state;
6419
+ const key = typeof state?.documentId === "string" && Number.isSafeInteger(state.revision) ? `${state.documentId}:${state.revision}` : null;
6420
+ if (key && fullPreview(item) && record.asset) previews.set(key, record.asset);
6421
+ if (item.arguments?.action === "finish") {
6422
+ asset = record.asset ?? (key ? previews.get(key) : void 0);
6423
+ if (asset) sketchOutputs.add(asset.fileId);
6424
+ }
6425
+ }
6426
+ if (asset) {
6427
+ if (!outputs.some((output) => output.fileId === asset.fileId)) outputs.push(asset);
6428
+ lastOutput = index;
6429
+ }
6430
+ }
6431
+ if (outputs.length === 0) return turn;
6432
+ const answer = turn.items.findLastIndex((item, index) => index > lastOutput && item.type === "agentMessage");
6433
+ if (answer < 0) return turn;
6434
+ const item = turn.items[answer];
6435
+ let text = item.text;
6436
+ for (const [fileId, previousUrl] of renderedSources.get(item) ?? []) {
6437
+ const current = outputs.find((output) => output.fileId === fileId);
6438
+ if (current && current.downloadUrl !== previousUrl) text = text.replaceAll(previousUrl, current.downloadUrl);
6439
+ }
6440
+ const presented = turn.items.filter((item) => item.type === "dynamicToolCall" && item.tool === "present").flatMap((item) => item.arguments?.files ?? []).map((file) => file.path).filter((path) => typeof path === "string");
6441
+ if (outputs.length === 1 && sketchOutputs.has(outputs[0].fileId)) text = text.replace(/!\[([^\]]*)\]\(([^)]+)\)/gu, (whole, alt, source) => {
6442
+ const ref = source.trim().replace(/^<|>$/gu, "");
6443
+ return presented.some((path) => matchesPresentedPath(path, ref)) ? `![${alt}](${outputs[0].downloadUrl})` : whole;
6444
+ });
6445
+ for (const asset of outputs) if (!text.includes(asset.downloadUrl)) text += `\n\n![Image](${asset.downloadUrl})`;
6446
+ const sources = new Map(outputs.map((asset) => [asset.fileId, asset.downloadUrl]));
6447
+ renderedSources.set(item, sources);
6448
+ if (text === item.text) return turn;
6449
+ const rendered = {
6450
+ ...item,
6451
+ text
6452
+ };
6453
+ renderedSources.set(rendered, sources);
6454
+ return {
6455
+ ...turn,
6456
+ items: turn.items.map((entry, index) => index === answer ? rendered : entry)
6457
+ };
6458
+ }
6459
+ //#endregion
6258
6460
  //#region src/remote-control-dsh.js
6259
6461
  /** A folder the phone named, only when it is an existing absolute folder on this machine. */
6260
6462
  function localFolder(value) {
@@ -6512,7 +6714,7 @@ function toolItem(block, cwd) {
6512
6714
  };
6513
6715
  }
6514
6716
  /** Record a tool's result on the item that showed the call. */
6515
- function finishTool(item, message, imageUrls) {
6717
+ function finishTool(item, message, imageUrls, imageAssets = /* @__PURE__ */ new Map()) {
6516
6718
  const failed = Boolean(message.isError);
6517
6719
  item.status = failed ? "failed" : "completed";
6518
6720
  if (item.type === "commandExecution") {
@@ -6521,9 +6723,11 @@ function finishTool(item, message, imageUrls) {
6521
6723
  } else if (item.type === "imageGeneration") {
6522
6724
  const url = imageBlocks(message).map((block) => imageUrls.get(block.attachment.attachmentId)).find(Boolean);
6523
6725
  item.result = url ? url.slice(url.indexOf(",") + 1) : "";
6726
+ const asset = imageBlocks(message).map((block) => imageAssets.get(block.attachment.attachmentId)).find(Boolean);
6727
+ if (asset) item.fileId = asset.fileId;
6524
6728
  if (!url) item.status = "failed";
6525
6729
  } else if (item.type === "dynamicToolCall") {
6526
- item.contentItems = toolOutput(message, imageUrls);
6730
+ item.contentItems = toolOutput(message, imageUrls, imageAssets);
6527
6731
  item.success = !failed;
6528
6732
  } else if (item.type === "mcpToolCall") {
6529
6733
  const text = textOf(message.content);
@@ -6536,12 +6740,13 @@ function finishTool(item, message, imageUrls) {
6536
6740
  structuredContent: null
6537
6741
  };
6538
6742
  }
6743
+ rememberRemoteImage(item, message, imageAssets);
6539
6744
  }
6540
6745
  const imageBlocks = (message) => (message.content ?? []).filter((block) => block?.type === "image" && block.attachment);
6541
- const toolOutput = (message, imageUrls) => [{
6746
+ const toolOutput = (message, imageUrls, imageAssets) => [{
6542
6747
  type: "inputText",
6543
6748
  text: textOf(message.content)
6544
- }, ...imageBlocks(message).map((block) => imageUrls.get(block.attachment.attachmentId)).filter(Boolean).map((imageUrl) => ({
6749
+ }, ...imageBlocks(message).map((block) => imageAssets.get(block.attachment.attachmentId)?.downloadUrl ?? imageUrls.get(block.attachment.attachmentId)).filter(Boolean).map((imageUrl) => ({
6545
6750
  type: "inputImage",
6546
6751
  imageUrl
6547
6752
  }))];
@@ -6549,7 +6754,7 @@ const toolOutput = (message, imageUrls) => [{
6549
6754
  /** Images the person attached to a message of their own. */
6550
6755
  const typedImages = (message) => message.role === "user" && (message.source === void 0 || message.source?.kind === "user") ? (message.content ?? []).filter((block) => block?.type === "image" && block.attachment) : [];
6551
6756
  /** `imageUrls` maps an attachment id to a data URL the phone can show; images without one are left out. */
6552
- function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0) {
6757
+ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0, imageAssets = /* @__PURE__ */ new Map()) {
6553
6758
  const turns = [];
6554
6759
  let turn;
6555
6760
  const calls = /* @__PURE__ */ new Map();
@@ -6563,7 +6768,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
6563
6768
  };
6564
6769
  for (const message of messages) if (message.role === "user") {
6565
6770
  const text = typedText(message);
6566
- const pictures = typedImages(message).map((block) => imageUrls.get(block.attachment.attachmentId)).filter(Boolean);
6771
+ const pictures = typedImages(message).map((block) => imageAssets.get(block.attachment.attachmentId)?.downloadUrl ?? imageUrls.get(block.attachment.attachmentId)).filter(Boolean);
6567
6772
  if (text === "" && pictures.length === 0) continue;
6568
6773
  close();
6569
6774
  turn = {
@@ -6613,10 +6818,10 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
6613
6818
  }
6614
6819
  } else if (message.role === "tool") {
6615
6820
  const item = calls.get(message.toolCallId);
6616
- if (item) finishTool(item, message, imageUrls);
6821
+ if (item) finishTool(item, message, imageUrls, imageAssets);
6617
6822
  }
6618
6823
  close();
6619
- return turns;
6824
+ return turns.map(withRemoteImageOutput);
6620
6825
  }
6621
6826
  function thread({ id, title, preview, cwd, createdAt, updatedAt, running, turns = [], projectId = null, threadSource = "dsh" }) {
6622
6827
  return {
@@ -6742,7 +6947,7 @@ function createPhoneConfig(file) {
6742
6947
  }
6743
6948
  };
6744
6949
  }
6745
- function createDshRemoteControl({ controller, agents, permissions = () => void 0, workspaces = () => void 0, attachments = () => void 0, usage = () => void 0, usageProfile = () => void 0, projections = () => void 0, skills = () => void 0, commands = () => void 0, llm = () => void 0, speed = void 0, trace = () => {}, phoneReturnMs = PHONE_RETURN_MS, userAgent, appServerUserAgent = userAgent, configFile = void 0, voice = void 0 }) {
6950
+ function createDshRemoteControl({ controller, agents, permissions = () => void 0, workspaces = () => void 0, attachments = () => void 0, remoteImages = void 0, imagePublishMs = 2e4, usage = () => void 0, usageProfile = () => void 0, projections = () => void 0, skills = () => void 0, commands = () => void 0, llm = () => void 0, speed = void 0, trace = () => {}, phoneReturnMs = PHONE_RETURN_MS, userAgent, appServerUserAgent = userAgent, configFile = void 0, voice = void 0 }) {
6746
6951
  const subscribers = /* @__PURE__ */ new Map();
6747
6952
  const threadSources = /* @__PURE__ */ new Map();
6748
6953
  const active = /* @__PURE__ */ new Map();
@@ -6787,7 +6992,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6787
6992
  signal?.addEventListener("abort", stop, { once: true });
6788
6993
  });
6789
6994
  const emit = (threadId, method, params) => {
6790
- for (const notify of subscribers.get(threadId) ?? []) notify(method, params).catch(() => {});
6995
+ for (const notify of subscribers.get(threadId) ?? []) notify(method, params).catch((error) => {
6996
+ phoneLog("thread notification failed", {
6997
+ method,
6998
+ threadId,
6999
+ error: error?.message
7000
+ }, "error");
7001
+ });
6791
7002
  };
6792
7003
  const agentFor = async (id) => {
6793
7004
  const result = await service().resolveAgent(id);
@@ -6906,31 +7117,104 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6906
7117
  recencyAt: entry.sessionIds?.length ? seconds(entry.updatedAt) : null
6907
7118
  });
6908
7119
  /** Data URLs for the images in a conversation (newest first, bounded), so the phone can show them. */
6909
- const imageUrlsOf = async (messages) => {
6910
- const urls = /* @__PURE__ */ new Map();
7120
+ const imageUrlsOf = async (messages, parentSignal) => {
7121
+ const urls = /* @__PURE__ */ new Map(), assets = /* @__PURE__ */ new Map();
6911
7122
  const store = attachments();
6912
- if (!store) return urls;
6913
- const wanted = messages.flatMap((message) => message.role === "tool" || typedImages(message).length > 0 ? imageBlocks(message) : []).toReversed().slice(0, 12);
7123
+ if (!store) {
7124
+ if (messages.some((message) => imageBlocks(message).length)) phoneLog("image store unavailable", { images: messages.flatMap(imageBlocks).length }, "warn");
7125
+ return {
7126
+ urls,
7127
+ assets
7128
+ };
7129
+ }
7130
+ const recentUnique = (blocks) => [...new Map(blocks.toReversed().map((block) => [block.attachment.attachmentId, block])).values()].slice(0, 12);
7131
+ const userImages = recentUnique(messages.flatMap(typedImages));
7132
+ const toolImages = recentUnique(messages.filter((message) => message.role === "tool").flatMap(imageBlocks));
7133
+ const balanced = [
7134
+ ...userImages.slice(0, 6),
7135
+ ...toolImages.slice(0, 6),
7136
+ ...userImages.slice(6),
7137
+ ...toolImages.slice(6)
7138
+ ];
7139
+ const wanted = [...new Map(balanced.map((block) => [block.attachment.attachmentId, block])).values()].slice(0, 12);
6914
7140
  await Promise.all(wanted.map(async (block) => {
7141
+ const started = Date.now();
6915
7142
  try {
6916
7143
  const stored = await store.readImage(block.attachment, AbortSignal.timeout(1e4));
6917
7144
  urls.set(block.attachment.attachmentId, `data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
6918
- } catch {}
7145
+ phoneLog("image read completed", {
7146
+ attachmentId: block.attachment.attachmentId,
7147
+ bytes: stored.data.byteLength,
7148
+ ms: Date.now() - started
7149
+ });
7150
+ if (remoteImages) {
7151
+ const signal = AbortSignal.any([AbortSignal.timeout(imagePublishMs), ...parentSignal ? [parentSignal] : []]);
7152
+ try {
7153
+ const asset = await remoteImages.publish({
7154
+ data: stored.data,
7155
+ mediaType: stored.ref.mediaType
7156
+ }, signal);
7157
+ signal.throwIfAborted();
7158
+ assets.set(block.attachment.attachmentId, asset);
7159
+ phoneLog("image publication completed", {
7160
+ attachmentId: block.attachment.attachmentId,
7161
+ bytes: stored.data.byteLength
7162
+ });
7163
+ } catch {
7164
+ phoneLog("image publication unavailable", {
7165
+ attachmentId: block.attachment.attachmentId,
7166
+ code: parentSignal?.aborted ? "cancelled" : signal.aborted ? "timeout" : "publish-failed"
7167
+ }, "warn");
7168
+ }
7169
+ }
7170
+ } catch (error) {
7171
+ phoneLog("image read failed", {
7172
+ attachmentId: block.attachment.attachmentId,
7173
+ ms: Date.now() - started,
7174
+ error: error?.message
7175
+ }, "warn");
7176
+ }
6919
7177
  }));
6920
- return urls;
7178
+ return {
7179
+ urls,
7180
+ assets
7181
+ };
6921
7182
  };
6922
7183
  /** The turn DSH is running, as the phone should see it now: what is committed, plus the reply still being written. */
6923
7184
  const aliases = /* @__PURE__ */ new Map();
7185
+ const turnAliases = /* @__PURE__ */ new Map();
7186
+ const clientAliases = /* @__PURE__ */ new Map();
6924
7187
  const keepShownId = (threadId, committed, shown) => {
6925
7188
  if (committed === shown) return;
6926
7189
  aliases.set(`${threadId}\0${committed}`, shown);
6927
7190
  if (aliases.size > 2e3) aliases.delete(aliases.keys().next().value);
6928
7191
  };
6929
- const withShownIds = (id, turns) => aliases.size === 0 ? turns : turns.map((turn) => ({
7192
+ const reconcileUser = (id, live, message) => {
7193
+ if (!message || live.committedUserId || live.priorMessageIds.has(message.id)) return;
7194
+ const text = visibleText(live.userItem.content.filter((part) => part.type === "text"));
7195
+ if (message.role !== "user" || typedText(message) !== text || typedImages(message).length !== live.userItem.content.filter((part) => part.type === "image").length) return;
7196
+ live.committedUserId = message.id;
7197
+ keepShownId(id, message.id, live.userItem.id);
7198
+ turnAliases.set(`${id}\0${message.id}`, live.turn.id);
7199
+ if (turnAliases.size > 2e3) turnAliases.delete(turnAliases.keys().next().value);
7200
+ if (live.userItem.clientId !== null) {
7201
+ clientAliases.set(`${id}\0${message.id}`, live.userItem.clientId);
7202
+ if (clientAliases.size > 2e3) clientAliases.delete(clientAliases.keys().next().value);
7203
+ }
7204
+ phoneLog("user message reconciled", {
7205
+ threadId: id,
7206
+ turnId: live.turn.id,
7207
+ itemId: live.userItem.id,
7208
+ matched: true
7209
+ });
7210
+ };
7211
+ const withShownIds = (id, turns) => turns.map((turn) => ({
6930
7212
  ...turn,
7213
+ id: turnAliases.get(`${id}\0${turn.id}`) ?? turn.id,
6931
7214
  items: turn.items.map((item) => aliases.has(`${id}\0${item.id}`) ? {
6932
7215
  ...item,
6933
- id: aliases.get(`${id}\0${item.id}`)
7216
+ id: aliases.get(`${id}\0${item.id}`),
7217
+ ...item.type === "userMessage" ? { clientId: clientAliases.get(`${id}\0${item.id}`) ?? null } : {}
6934
7218
  } : item)
6935
7219
  }));
6936
7220
  const withLiveTurn = (id, shownTurns) => {
@@ -6944,7 +7228,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6944
7228
  text: writing.text
6945
7229
  }] : [];
6946
7230
  const last = turns.at(-1);
6947
- const ours = last?.items[0]?.type === "userMessage" && typed(last.items[0]) === typed(live.userItem);
7231
+ const ours = last?.items[0]?.type === "userMessage" && (last.items[0].id === live.userItem.id || !live.priorMessageIds.has(last.items[0].id) && typed(last.items[0]) === typed(live.userItem));
6948
7232
  const items = ours ? [
6949
7233
  live.userItem,
6950
7234
  ...last.items.slice(1),
@@ -6959,16 +7243,20 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6959
7243
  durationMs: null
6960
7244
  }];
6961
7245
  };
6962
- const openThread = async (id, notify) => {
7246
+ const openThread = async (id, notify, signal) => {
7247
+ const started = Date.now();
7248
+ phoneLog("history restore started", { threadId: id });
6963
7249
  const agent = await agentFor(id);
6964
7250
  if (notify) subscribe(id, notify);
6965
7251
  await (catalog ? void 0 : loadCatalog().catch(() => void 0));
6966
7252
  const session = agent.session;
6967
7253
  const messages = session.deriveMessages();
7254
+ const live = active.get(id);
7255
+ if (live?.userItem) for (const message of messages) reconcileUser(id, live, message);
6968
7256
  const first = messages.find((message) => typedText(message) !== "");
6969
- const imageUrls = await imageUrlsOf(messages);
7257
+ const { urls: imageUrls, assets: imageAssets } = await imageUrlsOf(messages, signal);
6970
7258
  const cwd = directoryOf(session);
6971
- return {
7259
+ const result = {
6972
7260
  agent,
6973
7261
  thread: thread({
6974
7262
  id,
@@ -6978,9 +7266,17 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6978
7266
  projectId: projectIdOf(id),
6979
7267
  threadSource: threadSources.get(id),
6980
7268
  preview: first ? visibleText(first.content).slice(0, 200) : "",
6981
- turns: withLiveTurn(id, projectTurns(messages, session.meta?.createdAt, imageUrls, cwd))
7269
+ turns: withLiveTurn(id, projectTurns(messages, session.meta?.createdAt, imageUrls, cwd, imageAssets))
6982
7270
  })
6983
7271
  };
7272
+ phoneLog("history restore completed", {
7273
+ threadId: id,
7274
+ ms: Date.now() - started,
7275
+ items: messages.length,
7276
+ turns: result.thread.turns.length,
7277
+ images: imageUrls.size
7278
+ });
7279
+ return result;
6984
7280
  };
6985
7281
  /** Apply a model or effort the phone picked; DSH validates it against its own catalog. */
6986
7282
  const TIER_OF = {
@@ -7160,7 +7456,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7160
7456
  const turn = emptyTurn();
7161
7457
  const userItem = {
7162
7458
  type: "userMessage",
7163
- id: params.clientUserMessageId ?? randomUUID(),
7459
+ id: randomUUID(),
7164
7460
  clientId: params.clientUserMessageId ?? null,
7165
7461
  content: [...text === "" ? [] : [{
7166
7462
  type: "text",
@@ -7171,10 +7467,21 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7171
7467
  url: picture.url
7172
7468
  }))]
7173
7469
  };
7174
- active.set(id, {
7470
+ const running = {
7175
7471
  turn,
7176
7472
  ended: void 0,
7177
- userItem
7473
+ userItem,
7474
+ priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
7475
+ pendingImages: /* @__PURE__ */ new Set(),
7476
+ abort: new AbortController()
7477
+ };
7478
+ active.set(id, running);
7479
+ phoneLog("turn accepted", {
7480
+ threadId: id,
7481
+ turnId: turn.id,
7482
+ itemId: userItem.id,
7483
+ hasClientId: userItem.clientId !== null,
7484
+ images: pictures.length
7178
7485
  });
7179
7486
  emit(id, "turn/started", {
7180
7487
  threadId: id,
@@ -7211,7 +7518,14 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7211
7518
  active.delete(id);
7212
7519
  throw new RpcError(-32603, error?.message ? `DSH did not accept the message: ${String(error.message).slice(0, 200)}` : "DSH did not accept the message");
7213
7520
  }
7214
- Promise.resolve(agent.whenIdle?.()).catch(() => {}).then(() => {
7521
+ Promise.resolve(agent.whenIdle?.()).catch(() => {}).then(async () => {
7522
+ if (running.pendingImages.size) phoneLog("waiting for tool images", {
7523
+ threadId: id,
7524
+ turnId: turn.id,
7525
+ pending: running.pendingImages.size
7526
+ });
7527
+ await Promise.allSettled([...running.pendingImages]);
7528
+ turn.items = withRemoteImageOutput(turn).items;
7215
7529
  const reason = active.get(id)?.ended;
7216
7530
  turn.status = reason?.kind === "error" ? "failed" : reason?.kind === "aborted" || reason?.kind === "interrupted" ? "interrupted" : "completed";
7217
7531
  if (reason?.kind === "error") {
@@ -7230,10 +7544,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7230
7544
  }
7231
7545
  turn.completedAt = seconds(Date.now());
7232
7546
  if (speedForTurn !== void 0 && speedBefore !== void 0 && speed?.current?.() !== speedBefore) Promise.resolve(speed.set?.(speedBefore)).catch(() => {});
7233
- const sentText = visibleText(userItem.content.filter((part) => part.type === "text"));
7234
7547
  try {
7235
- const committedUser = agent.session.deriveMessages().findLast((message) => typedText(message) !== "" && typedText(message) === sentText);
7236
- if (committedUser) keepShownId(id, committedUser.id, userItem.id);
7548
+ for (const message of agent.session.deriveMessages()) reconcileUser(id, running, message);
7237
7549
  } catch {}
7238
7550
  active.delete(id);
7239
7551
  compactions.delete(id);
@@ -7247,6 +7559,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7247
7559
  threadId: id,
7248
7560
  turn
7249
7561
  });
7562
+ phoneLog("turn completed", {
7563
+ threadId: id,
7564
+ turnId: turn.id,
7565
+ status: turn.status,
7566
+ items: turn.items.length
7567
+ });
7250
7568
  emit(id, "thread/status/changed", {
7251
7569
  threadId: id,
7252
7570
  status: { type: "idle" }
@@ -7262,7 +7580,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7262
7580
  }, notify).catch(() => {});
7263
7581
  }
7264
7582
  });
7265
- return { turn };
7583
+ return { turn: {
7584
+ ...turn,
7585
+ items: []
7586
+ } };
7266
7587
  }
7267
7588
  /** Conversations the phone may see, filtered the way it asks, plus the passages DSH found for a search term. */
7268
7589
  const listed = async (params, signal) => {
@@ -7443,6 +7764,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7443
7764
  };
7444
7765
  },
7445
7766
  "command/exec": async (params, { notify, signal }) => {
7767
+ const command = Array.isArray(params?.command) ? params.command.filter((part) => typeof part === "string") : [];
7768
+ const executable = command[0]?.replaceAll("\\", "/").split("/").at(-1) ?? "";
7769
+ phoneLog("command request classified", {
7770
+ type: /^(?:git|powershell|pwsh|bash|sh)(?:\.exe)?$/iu.test(executable) ? executable.toLowerCase().replace(/\.exe$/u, "") : "other",
7771
+ items: command.length,
7772
+ images: command.some((part) => /ReadAllBytes|ToBase64String|\bbase64\b/iu.test(part)) ? 1 : 0
7773
+ });
7446
7774
  const home = homeFolderAnswer(params?.command);
7447
7775
  if (home !== void 0) return home;
7448
7776
  const folders = await conversationFolders();
@@ -7453,6 +7781,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7453
7781
  signal
7454
7782
  }) : await runGit(params, { folders });
7455
7783
  } catch (error) {
7784
+ phoneLog("command request refused", { code: error?.code ?? error?.name }, "warn");
7456
7785
  trace({
7457
7786
  method: "command/exec:refused",
7458
7787
  reason: String(error?.message).slice(0, 80),
@@ -7705,9 +8034,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7705
8034
  await registry.unarchiveSession(params?.threadId);
7706
8035
  return { thread: (await openThread(params?.threadId)).thread };
7707
8036
  },
7708
- "thread/read": async (params) => ({ thread: (await openThread(params?.threadId)).thread }),
7709
- "thread/resume": async (params, { notify }) => {
7710
- const { agent, thread: value } = await openThread(params?.threadId, notify);
8037
+ "thread/read": async (params, { signal } = {}) => ({ thread: (await openThread(params?.threadId, void 0, signal)).thread }),
8038
+ "thread/resume": async (params, { notify, signal }) => {
8039
+ const { agent, thread: value } = await openThread(params?.threadId, notify, signal);
7711
8040
  return {
7712
8041
  ...settings(agent, value.cwd),
7713
8042
  thread: value
@@ -8065,10 +8394,21 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8065
8394
  const id = session.id;
8066
8395
  if (frame.type === "start") {
8067
8396
  streams.delete(id);
8397
+ phoneLog("assistant stream started", {
8398
+ threadId: id,
8399
+ turnId: running.turn.id
8400
+ });
8068
8401
  return;
8069
8402
  }
8070
8403
  if (frame.type === "end") {
8071
8404
  const stream = streams.get(id);
8405
+ phoneLog("assistant stream ended", {
8406
+ threadId: id,
8407
+ turnId: running.turn.id,
8408
+ chunks: stream?.chunks ?? 0,
8409
+ bytes: Buffer.byteLength(stream?.text ?? ""),
8410
+ status: frame.outcome?.kind
8411
+ });
8072
8412
  if (stream && frame.outcome?.eventType !== "assistant/message") {
8073
8413
  streams.delete(id);
8074
8414
  stream.item.text = stream.text;
@@ -8094,7 +8434,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8094
8434
  memoryCitation: null,
8095
8435
  delivery: null
8096
8436
  },
8097
- text: ""
8437
+ text: "",
8438
+ chunks: 0
8098
8439
  };
8099
8440
  streams.set(id, stream);
8100
8441
  running.turn.items.push(stream.item);
@@ -8106,6 +8447,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8106
8447
  });
8107
8448
  }
8108
8449
  stream.text += chunk.text;
8450
+ stream.chunks++;
8109
8451
  emit(id, "item/agentMessage/delta", {
8110
8452
  threadId: id,
8111
8453
  turnId: running.turn.id,
@@ -8121,6 +8463,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8121
8463
  });
8122
8464
  const running = active.get(session.id);
8123
8465
  if (!running || !subscribers.has(session.id)) return;
8466
+ if (event.type === "user/message" && running.userItem) {
8467
+ reconcileUser(session.id, running, {
8468
+ role: "user",
8469
+ ...event.data
8470
+ });
8471
+ return;
8472
+ }
8124
8473
  if (event.type === "turn/end") {
8125
8474
  running.ended = event.data?.reason;
8126
8475
  return;
@@ -8152,12 +8501,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8152
8501
  return;
8153
8502
  }
8154
8503
  if (event.type !== "assistant/message" && event.type !== "tool/result") return;
8155
- const message = session.deriveMessages().at(-1);
8504
+ const message = event.data?.message ?? session.deriveMessages().at(-1);
8156
8505
  if (message?.role === "tool") {
8157
8506
  const item = running.turn.items.find((entry) => entry.id === message.toolCallId && entry.type !== "agentMessage");
8158
8507
  if (item) {
8159
- const finish = (imageUrls) => {
8160
- finishTool(item, message, imageUrls);
8508
+ const finish = ({ urls, assets }) => {
8509
+ finishTool(item, message, urls, assets);
8161
8510
  emit(session.id, "item/completed", {
8162
8511
  threadId: session.id,
8163
8512
  turnId: running.turn.id,
@@ -8165,8 +8514,25 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8165
8514
  completedAtMs: Date.now()
8166
8515
  });
8167
8516
  };
8168
- if (imageBlocks(message).length > 0) imageUrlsOf([message]).then(finish, () => finish(/* @__PURE__ */ new Map()));
8169
- else finish(/* @__PURE__ */ new Map());
8517
+ if (imageBlocks(message).length > 0) {
8518
+ const pending = imageUrlsOf([message], running.abort.signal).then(finish, () => finish({
8519
+ urls: /* @__PURE__ */ new Map(),
8520
+ assets: /* @__PURE__ */ new Map()
8521
+ }));
8522
+ running.pendingImages ??= /* @__PURE__ */ new Set();
8523
+ running.pendingImages.add(pending);
8524
+ pending.then(() => running.pendingImages.delete(pending), (error) => {
8525
+ running.pendingImages.delete(pending);
8526
+ phoneLog("tool image delivery failed", {
8527
+ threadId: session.id,
8528
+ itemId: item.id,
8529
+ error: error?.message
8530
+ }, "error");
8531
+ });
8532
+ } else finish({
8533
+ urls: /* @__PURE__ */ new Map(),
8534
+ assets: /* @__PURE__ */ new Map()
8535
+ });
8170
8536
  }
8171
8537
  return;
8172
8538
  }
@@ -8179,6 +8545,27 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8179
8545
  text: "x"
8180
8546
  }]
8181
8547
  }, message], void 0, void 0, directoryOf(session)).flatMap((turn) => turn.items.slice(1));
8548
+ const toolIds = new Set(message.content.filter((block) => block.type === "tool-call").map((block) => block.id));
8549
+ const completeText = (item) => {
8550
+ const finish = () => {
8551
+ const projected = withRemoteImageOutput(running.turn).items.find((entry) => entry.id === item.id);
8552
+ if (projected) item.text = projected.text;
8553
+ emit(session.id, "item/completed", {
8554
+ threadId: session.id,
8555
+ turnId: running.turn.id,
8556
+ item,
8557
+ completedAtMs: Date.now()
8558
+ });
8559
+ };
8560
+ const pending = toolIds.size === 0 ? [...running.pendingImages ?? []] : [];
8561
+ if (pending.length === 0) {
8562
+ finish();
8563
+ return;
8564
+ }
8565
+ const job = Promise.allSettled(pending).then(finish);
8566
+ running.pendingImages.add(job);
8567
+ job.then(() => running.pendingImages.delete(job), () => running.pendingImages.delete(job));
8568
+ };
8182
8569
  const stream = streams.get(session.id);
8183
8570
  streams.delete(session.id);
8184
8571
  let reuse = stream?.item;
@@ -8207,12 +8594,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8207
8594
  reuse = void 0;
8208
8595
  keepShownId(session.id, item.id, shown.id);
8209
8596
  shown.text = item.text;
8210
- emit(session.id, "item/completed", {
8211
- threadId: session.id,
8212
- turnId: running.turn.id,
8213
- item: shown,
8214
- completedAtMs: Date.now()
8215
- });
8597
+ completeText(shown);
8216
8598
  continue;
8217
8599
  }
8218
8600
  running.turn.items.push(item);
@@ -8222,7 +8604,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8222
8604
  item,
8223
8605
  startedAtMs: Date.now()
8224
8606
  });
8225
- emit(session.id, "item/completed", {
8607
+ if (item.type === "agentMessage") completeText(item);
8608
+ else if (!toolIds.has(item.id)) emit(session.id, "item/completed", {
8226
8609
  threadId: session.id,
8227
8610
  turnId: running.turn.id,
8228
8611
  item,
@@ -8299,6 +8682,253 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8299
8682
  };
8300
8683
  }
8301
8684
  //#endregion
8685
+ //#region src/remote-image-assets.js
8686
+ const BASE$1 = "https://chatgpt.com/backend-api/";
8687
+ const FILE_ID = /^file[-_][A-Za-z0-9_-]{1,200}$/u;
8688
+ const HASH = /^[a-f0-9]{64}$/u;
8689
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
8690
+ function imageBytes({ data, mediaType } = {}) {
8691
+ if (!(data instanceof Uint8Array) || data.byteLength === 0 || data.byteLength > 8 * 1024 * 1024) throw new Error("Invalid remote image size");
8692
+ const bytes = Buffer.from(data);
8693
+ const png = bytes.length >= 24 && bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a" && bytes.toString("ascii", 12, 16) === "IHDR" && bytes.readUInt32BE(16) > 0 && bytes.readUInt32BE(20) > 0;
8694
+ const jpeg = bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 && bytes.at(-2) === 255 && bytes.at(-1) === 217;
8695
+ if (!(mediaType === "image/png" && png || mediaType === "image/jpeg" && jpeg)) throw new Error("Remote image type does not match image bytes");
8696
+ return bytes;
8697
+ }
8698
+ function signedUrl(value) {
8699
+ let url;
8700
+ try {
8701
+ url = new URL(value);
8702
+ } catch {
8703
+ throw new Error("Invalid signed image destination");
8704
+ }
8705
+ if (url.protocol !== "https:" || url.username || url.password || url.port && url.port !== "443" || !/(?:\.blob\.core\.windows\.net|\.oaiusercontent\.com|\.openai\.com)$/u.test(url.hostname)) throw new Error("Untrusted signed image destination");
8706
+ return url.href;
8707
+ }
8708
+ function cachedEntry(value) {
8709
+ return value && HASH.test(value.hash) && FILE_ID.test(value.fileId) && Number.isSafeInteger(value.bytes) && value.bytes > 0 && value.bytes <= 8 * 1024 * 1024 && ["image/png", "image/jpeg"].includes(value.mediaType);
8710
+ }
8711
+ /** Private, account-scoped image upload cache. Persist only IDs and image metadata. */
8712
+ function createRemoteImageAssets({ credentials, fetch: request = globalThis.fetch, stateFile, timeoutMs = 3e4 } = {}) {
8713
+ const accounts = /* @__PURE__ */ new Map(), flights = /* @__PURE__ */ new Map();
8714
+ let writes = Promise.resolve();
8715
+ let ready;
8716
+ const load = () => ready ??= (async () => {
8717
+ if (!stateFile) return;
8718
+ let state;
8719
+ try {
8720
+ state = JSON.parse(await readFile(stateFile, "utf8"));
8721
+ } catch (error) {
8722
+ if (error.code === "ENOENT" || error instanceof SyntaxError) return;
8723
+ throw error;
8724
+ }
8725
+ if (state?.version !== 1 || !Array.isArray(state.accounts)) return;
8726
+ for (const account of state.accounts) {
8727
+ if (!HASH.test(account?.account)) continue;
8728
+ const entries = /* @__PURE__ */ new Map();
8729
+ for (const entry of (Array.isArray(account.images) ? account.images : []).slice(-128)) if (cachedEntry(entry)) entries.set(entry.hash, {
8730
+ hash: entry.hash,
8731
+ fileId: entry.fileId,
8732
+ bytes: entry.bytes,
8733
+ mediaType: entry.mediaType
8734
+ });
8735
+ accounts.set(account.account, entries);
8736
+ }
8737
+ })();
8738
+ const persist = () => {
8739
+ if (!stateFile) return Promise.resolve();
8740
+ const next = writes.catch(() => {}).then(async () => {
8741
+ const temporary = `${stateFile}.${randomUUID()}.tmp`;
8742
+ await mkdir(dirname(stateFile), {
8743
+ recursive: true,
8744
+ mode: 448
8745
+ });
8746
+ try {
8747
+ await writeFile(temporary, JSON.stringify({
8748
+ version: 1,
8749
+ accounts: [...accounts].map(([account, images]) => ({
8750
+ account,
8751
+ images: [...images.values()]
8752
+ }))
8753
+ }), {
8754
+ mode: 384,
8755
+ flag: "wx"
8756
+ });
8757
+ await rename(temporary, stateFile);
8758
+ } finally {
8759
+ await rm(temporary, { force: true });
8760
+ }
8761
+ });
8762
+ writes = next;
8763
+ return next;
8764
+ };
8765
+ const send = async (url, init) => {
8766
+ try {
8767
+ return await request(url, init);
8768
+ } catch {
8769
+ init.signal?.throwIfAborted();
8770
+ throw new Error("Remote image request failed");
8771
+ }
8772
+ };
8773
+ async function upload(bytes, mediaType, auth, owner, key, signal) {
8774
+ const api = async (method, path, body) => {
8775
+ signal.throwIfAborted();
8776
+ const response = await send(BASE$1 + path, {
8777
+ method,
8778
+ redirect: "error",
8779
+ signal: AbortSignal.any([signal, AbortSignal.timeout(6e4)]),
8780
+ headers: {
8781
+ authorization: `Bearer ${auth.access}`,
8782
+ "ChatGPT-Account-ID": auth.accountId,
8783
+ "content-type": "application/json"
8784
+ },
8785
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
8786
+ });
8787
+ if (!response.ok) {
8788
+ const error = /* @__PURE__ */ new Error(`Remote image ${method} failed (HTTP ${response.status})`);
8789
+ error.status = response.status;
8790
+ throw error;
8791
+ }
8792
+ try {
8793
+ return await response.json();
8794
+ } catch {
8795
+ throw new Error("Invalid remote image response");
8796
+ }
8797
+ };
8798
+ const finalize = async (fileId) => {
8799
+ for (let attempt = 0; attempt < 8; attempt++) {
8800
+ const completed = await api("POST", `files/${encodeURIComponent(fileId)}/uploaded`, {});
8801
+ if (completed.status === "success") return signedUrl(completed.download_url);
8802
+ if (completed.status !== "retry") throw new Error("Remote image finalization failed");
8803
+ if (attempt < 7) await setTimeout$1(250, void 0, { signal });
8804
+ }
8805
+ throw new Error("Remote image finalization did not complete");
8806
+ };
8807
+ let entries = accounts.get(owner);
8808
+ if (!entries) {
8809
+ entries = /* @__PURE__ */ new Map();
8810
+ accounts.set(owner, entries);
8811
+ }
8812
+ const saved = entries.get(key);
8813
+ if (saved) {
8814
+ try {
8815
+ return {
8816
+ fileId: saved.fileId,
8817
+ downloadUrl: await finalize(saved.fileId)
8818
+ };
8819
+ } catch (error) {
8820
+ if (error.status !== 404 && error.status !== 410) throw error;
8821
+ }
8822
+ entries.delete(key);
8823
+ }
8824
+ const created = await api("POST", "files", {
8825
+ file_name: `dsh-image-${key.slice(0, 16)}.${mediaType === "image/png" ? "png" : "jpg"}`,
8826
+ file_size: bytes.length,
8827
+ use_case: "codex"
8828
+ });
8829
+ if (!FILE_ID.test(created.file_id)) throw new Error("Invalid remote image file identity");
8830
+ const destination = signedUrl(created.upload_url);
8831
+ const put = await send(destination, {
8832
+ method: "PUT",
8833
+ redirect: "error",
8834
+ signal: AbortSignal.any([signal, AbortSignal.timeout(6e4)]),
8835
+ headers: {
8836
+ "x-ms-blob-type": "BlockBlob",
8837
+ "content-length": String(bytes.length),
8838
+ "content-type": mediaType
8839
+ },
8840
+ body: bytes
8841
+ });
8842
+ if (!put.ok) throw new Error(`Remote image upload failed (HTTP ${put.status})`);
8843
+ const downloadUrl = await finalize(created.file_id);
8844
+ signal.throwIfAborted();
8845
+ entries.set(key, {
8846
+ hash: key,
8847
+ fileId: created.file_id,
8848
+ bytes: bytes.length,
8849
+ mediaType
8850
+ });
8851
+ while (entries.size > 128) entries.delete(entries.keys().next().value);
8852
+ try {
8853
+ await persist();
8854
+ } catch (error) {
8855
+ entries.delete(key);
8856
+ throw error;
8857
+ }
8858
+ return {
8859
+ fileId: created.file_id,
8860
+ downloadUrl
8861
+ };
8862
+ }
8863
+ const publish = async (image, signal) => {
8864
+ signal?.throwIfAborted();
8865
+ const bytes = imageBytes(image);
8866
+ const credential = await credentials({ signal });
8867
+ const auth = {
8868
+ access: credential?.access,
8869
+ accountId: credential?.accountId
8870
+ };
8871
+ signal?.throwIfAborted();
8872
+ if (!auth?.access || typeof auth.access !== "string" || !auth.accountId || typeof auth.accountId !== "string") throw new Error("Remote image upload requires a signed-in account");
8873
+ await load();
8874
+ signal?.throwIfAborted();
8875
+ const owner = hash(auth.accountId), key = hash(bytes), flightKey = `${owner}:${key}`;
8876
+ let flight = flights.get(flightKey);
8877
+ if (!flight) {
8878
+ const controller = new AbortController();
8879
+ flight = {
8880
+ controller,
8881
+ waiters: 0,
8882
+ settled: false
8883
+ };
8884
+ flight.promise = Promise.resolve().then(() => upload(bytes, image.mediaType, auth, owner, key, controller.signal)).finally(() => {
8885
+ flight.settled = true;
8886
+ if (flights.get(flightKey) === flight) flights.delete(flightKey);
8887
+ });
8888
+ flights.set(flightKey, flight);
8889
+ }
8890
+ flight.waiters++;
8891
+ return new Promise((resolve, reject) => {
8892
+ let done = false;
8893
+ const finish = (error, value) => {
8894
+ if (done) return;
8895
+ done = true;
8896
+ signal?.removeEventListener("abort", abort);
8897
+ if (--flight.waiters === 0 && !flight.settled) {
8898
+ if (flights.get(flightKey) === flight) flights.delete(flightKey);
8899
+ flight.controller.abort();
8900
+ }
8901
+ if (error) reject(error);
8902
+ else resolve(value);
8903
+ };
8904
+ const abort = () => finish(signal.reason ?? /* @__PURE__ */ new Error("Remote image upload aborted"));
8905
+ signal?.addEventListener("abort", abort, { once: true });
8906
+ if (signal?.aborted) abort();
8907
+ flight.promise.then((value) => finish(void 0, value), (error) => finish(error));
8908
+ });
8909
+ };
8910
+ return Object.freeze({ publish(image, callerSignal) {
8911
+ const deadline = AbortSignal.timeout(timeoutMs);
8912
+ const signal = callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline;
8913
+ const operation = publish(image, signal);
8914
+ return new Promise((resolve, reject) => {
8915
+ const abort = () => {
8916
+ signal.removeEventListener("abort", abort);
8917
+ reject(signal.reason);
8918
+ };
8919
+ signal.addEventListener("abort", abort, { once: true });
8920
+ if (signal.aborted) abort();
8921
+ operation.then((value) => {
8922
+ signal.removeEventListener("abort", abort);
8923
+ resolve(value);
8924
+ }, (error) => {
8925
+ signal.removeEventListener("abort", abort);
8926
+ reject(error);
8927
+ });
8928
+ });
8929
+ } });
8930
+ }
8931
+ //#endregion
8302
8932
  //#region src/retry-policy.js
8303
8933
  /** @param {string} choice a RETRY_POLICIES value @param {Function | undefined} resolve DSH's resolveRetryPolicy */
8304
8934
  function retryPolicyFor(choice, resolve) {
@@ -9237,11 +9867,11 @@ const LEVELS = [
9237
9867
  "max"
9238
9868
  ];
9239
9869
  const DEFAULT_REFRESH_TIMEOUT_MS = 1e4;
9240
- const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9870
+ const record$6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9241
9871
  const nonEmpty$1 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
9242
9872
  const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 ? value : void 0;
9243
9873
  function upgradeModelId(value) {
9244
- return (typeof value.upgrade === "string" ? nonEmpty$1(value.upgrade) : record$7(value.upgrade) ? nonEmpty$1(value.upgrade.model) : void 0) ?? (record$7(value.upgrade_info) ? nonEmpty$1(value.upgrade_info.model) : void 0) ?? (record$7(value.upgradeInfo) ? nonEmpty$1(value.upgradeInfo.model) : void 0);
9874
+ return (typeof value.upgrade === "string" ? nonEmpty$1(value.upgrade) : record$6(value.upgrade) ? nonEmpty$1(value.upgrade.model) : void 0) ?? (record$6(value.upgrade_info) ? nonEmpty$1(value.upgrade_info.model) : void 0) ?? (record$6(value.upgradeInfo) ? nonEmpty$1(value.upgradeInfo.model) : void 0);
9245
9875
  }
9246
9876
  function retirementMillis(value) {
9247
9877
  for (const source of [
@@ -9250,7 +9880,7 @@ function retirementMillis(value) {
9250
9880
  value.upgrade_info,
9251
9881
  value.upgradeInfo
9252
9882
  ]) {
9253
- if (!record$7(source)) continue;
9883
+ if (!record$6(source)) continue;
9254
9884
  for (const raw of [source.retirement_at, source.retirementAt]) {
9255
9885
  const seconds = positiveInteger(raw);
9256
9886
  if (seconds !== void 0 && Number.isSafeInteger(seconds * 1e3)) return seconds * 1e3;
@@ -9262,7 +9892,7 @@ function retirementMillis(value) {
9262
9892
  }
9263
9893
  }
9264
9894
  function retirementNotice(value, now = Date.now(), targetDisplayName) {
9265
- if (!record$7(value) || !Number.isFinite(now)) return void 0;
9895
+ if (!record$6(value) || !Number.isFinite(now)) return void 0;
9266
9896
  const at = retirementMillis(value);
9267
9897
  if (at === void 0 || at <= now) return void 0;
9268
9898
  const date = new Date(at);
@@ -9278,7 +9908,7 @@ function retirementNotice(value, now = Date.now(), targetDisplayName) {
9278
9908
  };
9279
9909
  }
9280
9910
  function reasoningMap(levels) {
9281
- const supported = new Set((Array.isArray(levels) ? levels : []).map((level) => nonEmpty$1(record$7(level) ? level.effort : void 0)).filter(Boolean));
9911
+ const supported = new Set((Array.isArray(levels) ? levels : []).map((level) => nonEmpty$1(record$6(level) ? level.effort : void 0)).filter(Boolean));
9282
9912
  const map = Object.fromEntries(LEVELS.map((level) => [level, null]));
9283
9913
  if (supported.has("none")) map.off = "none";
9284
9914
  for (const level of LEVELS.slice(1)) if (supported.has(level)) map[level] = level;
@@ -9292,7 +9922,7 @@ const HONOURED_TIERS = /* @__PURE__ */ new Set([
9292
9922
  "ultrafast"
9293
9923
  ]);
9294
9924
  function serviceTierEntries(value) {
9295
- const found = (Array.isArray(value.service_tiers) ? value.service_tiers : []).flatMap((tier) => record$7(tier) && typeof tier.id === "string" && HONOURED_TIERS.has(tier.id) ? [{
9925
+ const found = (Array.isArray(value.service_tiers) ? value.service_tiers : []).flatMap((tier) => record$6(tier) && typeof tier.id === "string" && HONOURED_TIERS.has(tier.id) ? [{
9296
9926
  id: tier.id,
9297
9927
  name: nonEmpty$1(tier.name) ?? tier.id,
9298
9928
  description: nonEmpty$1(tier.description) ?? ""
@@ -9322,7 +9952,7 @@ function unsupportedCapabilities(value) {
9322
9952
  };
9323
9953
  }
9324
9954
  function visibleModel(value, displayNames, now) {
9325
- if (!record$7(value)) return void 0;
9955
+ if (!record$6(value)) return void 0;
9326
9956
  const id = nonEmpty$1(value.slug);
9327
9957
  const reserve = id === "gpt-reserve" && ["list", "hide"].includes(value.visibility);
9328
9958
  if (id === void 0 || value.visibility !== "list" && !reserve) return void 0;
@@ -9369,22 +9999,22 @@ function visibleModel(value, displayNames, now) {
9369
9999
  * visibility), with low reasoning when the reviewer supports it.
9370
10000
  */
9371
10001
  function officialReviewModel(value, parentId) {
9372
- if (!record$7(value) || !Array.isArray(value.models)) return void 0;
9373
- const parent = value.models.find((model) => record$7(model) && model.slug === parentId);
10002
+ if (!record$6(value) || !Array.isArray(value.models)) return void 0;
10003
+ const parent = value.models.find((model) => record$6(model) && model.slug === parentId);
9374
10004
  const id = nonEmpty$1(parent?.auto_review_model_override) ?? "codex-auto-review";
9375
- const preset = value.models.find((model) => record$7(model) && model.slug === id);
10005
+ const preset = value.models.find((model) => record$6(model) && model.slug === id);
9376
10006
  if (preset === void 0) return void 0;
9377
- const effort = (Array.isArray(preset.supported_reasoning_levels) ? preset.supported_reasoning_levels : []).some((level) => (record$7(level) ? level.effort : level) === "low") ? "low" : nonEmpty$1(preset.default_reasoning_level);
10007
+ const effort = (Array.isArray(preset.supported_reasoning_levels) ? preset.supported_reasoning_levels : []).some((level) => (record$6(level) ? level.effort : level) === "low") ? "low" : nonEmpty$1(preset.default_reasoning_level);
9378
10008
  return {
9379
10009
  id,
9380
10010
  ...effort === void 0 ? {} : { effort }
9381
10011
  };
9382
10012
  }
9383
10013
  function parseOfficialModelCatalog(value, now = Date.now()) {
9384
- if (!record$7(value) || !Array.isArray(value.models)) throw new Error("Codex returned a malformed model catalog");
10014
+ if (!record$6(value) || !Array.isArray(value.models)) throw new Error("Codex returned a malformed model catalog");
9385
10015
  const displayNames = /* @__PURE__ */ new Map();
9386
10016
  for (const model of value.models) {
9387
- if (!record$7(model)) continue;
10017
+ if (!record$6(model)) continue;
9388
10018
  const id = nonEmpty$1(model.slug);
9389
10019
  const name = nonEmpty$1(model.display_name);
9390
10020
  if (id !== void 0 && name !== void 0 && !displayNames.has(id)) displayNames.set(id, name);
@@ -9570,111 +10200,18 @@ function createOfficialModelCatalog(options = {}) {
9570
10200
  });
9571
10201
  }
9572
10202
  //#endregion
9573
- //#region src/deepseek-account-search.js
9574
- const DSH_ACCOUNT_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
9575
- const DEFAULT_BASE_URL = "https://api.deepseek.com/v1/tools";
9576
- const DEFAULT_COUNT = 10;
9577
- const MAX_QUESTION = 128;
9578
- const record$6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9579
- const missing = (message) => new WebError(message, "WEB_PROVIDER_CREDENTIAL_MISSING");
9580
- function parseSources(value) {
9581
- if (!record$6(value) || !Array.isArray(value.results)) throw new WebError("DeepSeek returned an invalid search response", "WEB_PROVIDER_ERROR");
9582
- return {
9583
- sources: value.results.flatMap((item) => {
9584
- if (!record$6(item) || typeof item.url !== "string" || item.url.length === 0) return [];
9585
- return [{
9586
- url: item.url,
9587
- ...typeof item.title === "string" && item.title.length > 0 ? { title: item.title } : {},
9588
- ...typeof item.snippet === "string" && item.snippet.length > 0 ? { snippet: item.snippet } : {},
9589
- ...typeof item.date === "string" && item.date.length > 0 ? { publishedAt: item.date } : {}
9590
- }];
9591
- }),
9592
- truncated: false
9593
- };
9594
- }
9595
- /**
9596
- * Search through DeepSeek's Search API with the signed-in DeepSeek account, for conversations whose
9597
- * model is not a DeepSeek Account one (DSH itself only hands the account token to those).
9598
- */
9599
- async function searchWithDeepSeekAccount(options, request, signal) {
9600
- signal?.throwIfAborted();
9601
- const account = options.resolveAccount?.();
9602
- if (typeof account?.resolveToken !== "function") throw missing("DeepSeek account sign-in is not available");
9603
- const config = options.resolveConfig?.() ?? {};
9604
- const baseURL = typeof config.baseURL === "string" && config.baseURL.length > 0 ? config.baseURL : DEFAULT_BASE_URL;
9605
- const count = Number.isInteger(config.count) && config.count > 0 ? config.count : DEFAULT_COUNT;
9606
- let endpoint;
9607
- try {
9608
- endpoint = `${new URL(baseURL).href.replace(/\/+$/u, "")}/search`;
9609
- } catch {
9610
- throw new WebError("DeepSeek search base URL is invalid", "WEB_PROVIDER_ERROR");
9611
- }
9612
- let token;
9613
- try {
9614
- token = await account.resolveToken(endpoint);
9615
- } catch {
9616
- throw missing("DeepSeek account sign-in could not be read");
9617
- }
9618
- if (typeof token !== "string" || token.length === 0) throw missing("DeepSeek account is not signed in");
9619
- const question = config.sendOriginalQuestion === false ? void 0 : Array.from((options.resolveQuestion?.() ?? "").replace(/\s+/gu, " ").trim()).slice(0, MAX_QUESTION).join("");
9620
- let response;
9621
- try {
9622
- response = await (options.fetch ?? fetch)(endpoint, {
9623
- method: "POST",
9624
- redirect: "error",
9625
- headers: {
9626
- "x-dsh-auth-token": token,
9627
- "content-type": "application/json",
9628
- accept: "application/json",
9629
- "user-agent": USER_AGENT
9630
- },
9631
- body: JSON.stringify({
9632
- query: request.query,
9633
- count: Math.min(count, request.maxResults ?? count),
9634
- need_content: false,
9635
- ...question ? { ori_question: question } : {}
9636
- }),
9637
- signal
9638
- });
9639
- } catch (error) {
9640
- if (signal?.aborted || error?.name === "AbortError") throw new WebError("DeepSeek web request aborted", "WEB_ABORTED", { cause: error });
9641
- throw new WebError("DeepSeek web request failed", "WEB_PROVIDER_ERROR", { cause: error });
9642
- }
9643
- if (!response.ok) throw response.status === 401 ? new WebError("DeepSeek rejected the account sign-in used for web search; sign in to DeepSeek again", "WEB_PROVIDER_ERROR") : new WebError(`DeepSeek search request failed (HTTP ${response.status})`, "WEB_PROVIDER_ERROR");
9644
- let body;
9645
- try {
9646
- body = await response.json();
9647
- } catch (error) {
9648
- throw new WebError("DeepSeek returned an unreadable search response", "WEB_PROVIDER_ERROR", { cause: error });
9649
- }
9650
- return parseSources(body);
9651
- }
9652
- /**
9653
- * The DSH search source with the account fallback: DSH's own provider goes first, and only when it
9654
- * reports a missing credential (no API key, model not a DeepSeek Account one) the account token is used.
9655
- */
9656
- function createDshAccountSearchProvider(options) {
10203
+ //#region src/dsh-search.js
10204
+ const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
10205
+ function createDshSearchProvider({ resolveDshProvider, report }) {
9657
10206
  return Object.freeze({
9658
- id: DSH_ACCOUNT_SEARCH_PROVIDER_ID,
10207
+ id: DSH_SEARCH_PROVIDER_ID,
9659
10208
  available: () => true,
9660
10209
  async search(request, signal) {
9661
- const provider = options.resolveDshProvider?.();
9662
- if (provider === void 0 || provider.id === "codex-subscription-dsh" || provider.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
9663
- try {
9664
- const result = await provider.search(request, signal);
9665
- options.report?.(`answered by DSH provider ${provider.id}`);
9666
- return result;
9667
- } catch (error) {
9668
- if (error?.code !== "WEB_PROVIDER_CREDENTIAL_MISSING" || signal?.aborted) throw error;
9669
- try {
9670
- const result = await searchWithDeepSeekAccount(options, request, signal);
9671
- options.report?.("answered by DeepSeek account fallback");
9672
- return result;
9673
- } catch (fallback) {
9674
- options.report?.(`DeepSeek account fallback failed: ${fallback?.message}`);
9675
- throw fallback?.code === "WEB_PROVIDER_CREDENTIAL_MISSING" ? error : fallback;
9676
- }
9677
- }
10210
+ const provider = resolveDshProvider?.();
10211
+ if (!provider || provider.id === "codex-subscription-dsh" || provider.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
10212
+ const result = await provider.search(request, signal);
10213
+ report?.(`answered by DSH provider ${provider.id}`);
10214
+ return result;
9678
10215
  }
9679
10216
  });
9680
10217
  }
@@ -9849,15 +10386,37 @@ function createCodexAutoSearchProvider(options) {
9849
10386
  const OWN_IDS = /* @__PURE__ */ new Set([
9850
10387
  CODEX_SEARCH_PROVIDER_ID,
9851
10388
  CODEX_AUTO_SEARCH_PROVIDER_ID,
9852
- DSH_ACCOUNT_SEARCH_PROVIDER_ID
10389
+ DSH_SEARCH_PROVIDER_ID
9853
10390
  ]);
10391
+ /** Guard the provider itself, including direct/cached handles and hosts without the registry proxy. */
10392
+ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
10393
+ const selected = () => {
10394
+ if (allowed()) return provider;
10395
+ const dsh = resolveDshProvider();
10396
+ if (!dsh || OWN_IDS.has(dsh.id) || dsh.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
10397
+ return dsh;
10398
+ };
10399
+ return Object.freeze({
10400
+ id: provider.id,
10401
+ available: () => {
10402
+ try {
10403
+ return selected().available();
10404
+ } catch {
10405
+ return false;
10406
+ }
10407
+ },
10408
+ async search(request, signal) {
10409
+ return selected().search(request, signal);
10410
+ }
10411
+ });
10412
+ }
9854
10413
  /**
9855
10414
  * Routes web search by the plugin's "search source" setting without touching which provider DSH has configured.
9856
10415
  *
9857
10416
  * The provider the user (or DSH's own settings page) picked stays the configured one, so DSH's settings keep showing
9858
10417
  * and saving what the user chose (for example the new Search API switch). Only the lookup of that one provider at
9859
10418
  * search time answers with a small router that sends the search to the Codex subscription, to the configured provider
9860
- * (with the DeepSeek account fallback), or by the conversation's model.
10419
+ * without an extra account fallback, or by the conversation's model.
9861
10420
  *
9862
10421
  * @returns {Map|undefined} a stand-in for the web registry, or undefined when the registry is not a Map.
9863
10422
  */
@@ -9888,10 +10447,6 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
9888
10447
  return typeof value === "function" ? value.bind(target) : value;
9889
10448
  } });
9890
10449
  }
9891
- /** With subscription features switched off for other models, an explicit Codex choice becomes automatic: Codex models still use Codex search, every other model uses DSH search. */
9892
- function effectiveSearchMode(mode, otherModels) {
9893
- return mode === "codex" && otherModels === "off" ? "auto" : mode;
9894
- }
9895
10450
  //#endregion
9896
10451
  //#region src/image-tool-registration.js
9897
10452
  /** Removing the tool also removes its schema from subsequent model requests. */
@@ -12913,7 +13468,7 @@ const DSH_SEARCH_PROVIDER_FALLBACK = "deepseek-official";
12913
13468
  const SUBSCRIPTION_SEARCH_PROVIDER_IDS = /* @__PURE__ */ new Set([
12914
13469
  CODEX_SEARCH_PROVIDER_ID,
12915
13470
  CODEX_AUTO_SEARCH_PROVIDER_ID,
12916
- DSH_ACCOUNT_SEARCH_PROVIDER_ID
13471
+ DSH_SEARCH_PROVIDER_ID
12917
13472
  ]);
12918
13473
  const MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
12919
13474
  const REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
@@ -12938,7 +13493,7 @@ function createSearchProviderSwitcher(loader) {
12938
13493
  searchProvider: provider
12939
13494
  }, true);
12940
13495
  };
12941
- const select = (selection) => writeProvider(selection === "codex" ? CODEX_SEARCH_PROVIDER_ID : selection === "auto" ? CODEX_AUTO_SEARCH_PROVIDER_ID : DSH_ACCOUNT_SEARCH_PROVIDER_ID);
13496
+ const select = (selection) => writeProvider(selection === "codex" ? CODEX_SEARCH_PROVIDER_ID : selection === "auto" ? CODEX_AUTO_SEARCH_PROVIDER_ID : DSH_SEARCH_PROVIDER_ID);
12942
13497
  return Object.freeze({
12943
13498
  dshProviderId,
12944
13499
  current,
@@ -13304,6 +13859,12 @@ function apply(ctx, config = {}) {
13304
13859
  const provider = currentAgent()?.session.requestContext?.()?.provider;
13305
13860
  return provider === void 0 || provider === PROVIDER;
13306
13861
  };
13862
+ const realSearchProviders = ctx.web.searchProviders;
13863
+ const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
13864
+ const gateSearch = (provider) => gateSearchProvider(provider, {
13865
+ allowed: () => settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER,
13866
+ resolveDshProvider: resolveDshSearch
13867
+ });
13307
13868
  const codexSearch = createCodexSearchProvider({
13308
13869
  resolvePreferences: () => readCapabilitySettings(settings.get()),
13309
13870
  getAuth: resolveAuth,
@@ -13316,7 +13877,7 @@ function apply(ctx, config = {}) {
13316
13877
  fetch: (input, init) => network.fetch("search", input, init)
13317
13878
  });
13318
13879
  const searchTrace = (route) => diagnosticLog.info("search", `web search: ${route}`);
13319
- const tracedCodexSearch = Object.freeze({
13880
+ const tracedCodexSearch = gateSearch({
13320
13881
  id: codexSearch.id,
13321
13882
  available: () => codexSearch.available(),
13322
13883
  async search(request, signal) {
@@ -13326,25 +13887,16 @@ function apply(ctx, config = {}) {
13326
13887
  }
13327
13888
  });
13328
13889
  ctx.web.registerSearchProvider(tracedCodexSearch);
13329
- const realSearchProviders = ctx.web.searchProviders;
13330
- const dshSearch = createDshAccountSearchProvider({
13890
+ const dshSearch = gateSearch(createDshSearchProvider({
13331
13891
  report: searchTrace,
13332
- resolveDshProvider: () => realSearchProviders?.get(searchProvider.dshProviderId()),
13333
- resolveAccount: () => ctx.get?.("deepseekAccount"),
13334
- resolveConfig: () => {
13335
- const config = [...ctx.loader.entries()].find((entry) => entry.options?.id === "web-deepseek-api")?.options?.config;
13336
- return config !== null && typeof config === "object" ? config : {};
13337
- },
13338
- resolveQuestion: () => {
13339
- return (currentAgent()?.session.deriveMessages?.() ?? []).findLast((message) => message.role === "user" && message.source?.kind === "user")?.content?.flatMap((block) => block.type === "text" ? [block.text] : []).join(" ");
13340
- }
13341
- });
13892
+ resolveDshProvider: resolveDshSearch
13893
+ }));
13342
13894
  ctx.web.registerSearchProvider(dshSearch);
13343
- const autoSearch = createCodexAutoSearchProvider({
13895
+ const autoSearch = gateSearch(createCodexAutoSearchProvider({
13344
13896
  codex: tracedCodexSearch,
13345
13897
  resolveModelProvider: () => currentAgent()?.session.requestContext?.()?.provider,
13346
13898
  resolveDshProvider: () => dshSearch
13347
- });
13899
+ }));
13348
13900
  ctx.web.registerSearchProvider(autoSearch);
13349
13901
  let searchRouted = false;
13350
13902
  ctx.effect(() => {
@@ -13352,7 +13904,7 @@ function apply(ctx, config = {}) {
13352
13904
  const router = createSearchRouter({
13353
13905
  registry: realSearchProviders,
13354
13906
  configuredId: () => searchProvider.current(),
13355
- mode: () => effectiveSearchMode(settings.get()[SEARCH_PROVIDER_FIELD], settings.get().otherModels),
13907
+ mode: () => settings.get()[SEARCH_PROVIDER_FIELD],
13356
13908
  providers: {
13357
13909
  codex: tracedCodexSearch,
13358
13910
  auto: autoSearch,
@@ -13406,6 +13958,14 @@ function apply(ctx, config = {}) {
13406
13958
  permissions: () => ctx.get?.("permissionPresets"),
13407
13959
  workspaces: () => ctx.get?.("workspaceRegistry"),
13408
13960
  attachments: () => ctx.attachments,
13961
+ remoteImages: createRemoteImageAssets({
13962
+ credentials: ({ signal }) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
13963
+ ...options,
13964
+ signal
13965
+ }), signal),
13966
+ fetch: (input, init) => network.fetch("remote", input, init),
13967
+ stateFile: dshHomePath("state", "codex-subscription", "remote-images.json")
13968
+ }),
13409
13969
  usage: () => usageReader,
13410
13970
  usageProfile: () => usageProfileReader,
13411
13971
  projections: () => ctx.get?.("sessionProjections"),