dsh-codex-subscription 3.1.3 → 3.1.4

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/README.en.md CHANGED
@@ -42,7 +42,7 @@ This plugin supports the latest DeepSeek Harness release recorded in its package
42
42
  2. Paste this package name, with its version, into the **Package name or address** field:
43
43
 
44
44
  ```text
45
- dsh-codex-subscription@3.1.3
45
+ dsh-codex-subscription@3.1.4
46
46
  ```
47
47
 
48
48
  3. Click **Install** and wait for completion. Follow the page instructions; save your work before restarting if requested.
@@ -54,7 +54,7 @@ Why the version is included: DSH's plugin page only installs versions that are a
54
54
  <summary>Terminal installation (with an existing dsh command)</summary>
55
55
 
56
56
  ```sh
57
- dsh plugin --profile web add dsh-codex-subscription@3.1.3
57
+ dsh plugin --profile web add dsh-codex-subscription@3.1.4
58
58
  ```
59
59
 
60
60
  Follow the restart instructions, then sign in under **Settings → Codex**. Both the Plugins page and the terminal use DSH's installation management.
@@ -67,7 +67,7 @@ Follow the restart instructions, then sign in under **Settings → Codex**. Both
67
67
  After signing in and selecting a Codex model in Web, install the same plugin in the Headless profile:
68
68
 
69
69
  ```sh
70
- dsh plugin --profile headless add dsh-codex-subscription@3.1.3
70
+ dsh plugin --profile headless add dsh-codex-subscription@3.1.4
71
71
  dsh --profile headless "Reply with only the word: ok"
72
72
  ```
73
73
 
@@ -294,7 +294,7 @@ Find this plugin on the DSH **Plugins** page and use its update or uninstall act
294
294
  <summary>Terminal commands</summary>
295
295
 
296
296
  ```sh
297
- dsh plugin --profile web update dsh-codex-subscription@3.1.3
297
+ dsh plugin --profile web update dsh-codex-subscription@3.1.4
298
298
  ```
299
299
 
300
300
  Run only when you want to uninstall:
package/README.md CHANGED
@@ -42,7 +42,7 @@
42
42
  2. 在 **包名或地址** 输入框中粘贴下面的包名(已带版本号):
43
43
 
44
44
  ```text
45
- dsh-codex-subscription@3.1.3
45
+ dsh-codex-subscription@3.1.4
46
46
  ```
47
47
 
48
48
  3. 点击 **安装**,等待安装完成;按页面提示操作,需要重启时先保存工作。
@@ -54,7 +54,7 @@
54
54
  <summary>终端安装(已能运行 dsh 命令)</summary>
55
55
 
56
56
  ```sh
57
- dsh plugin --profile web add dsh-codex-subscription@3.1.3
57
+ dsh plugin --profile web add dsh-codex-subscription@3.1.4
58
58
  ```
59
59
 
60
60
  安装完成后按提示重启 DSH,再到 **设置 → Codex 订阅** 登录。插件页面和终端均由 DSH 管理安装。
@@ -67,7 +67,7 @@ dsh plugin --profile web add dsh-codex-subscription@3.1.3
67
67
  先在 Web 中完成登录并选择一次 Codex 模型,再把同一个插件安装到 Headless profile:
68
68
 
69
69
  ```sh
70
- dsh plugin --profile headless add dsh-codex-subscription@3.1.3
70
+ dsh plugin --profile headless add dsh-codex-subscription@3.1.4
71
71
  dsh --profile headless "只回复:ok"
72
72
  ```
73
73
 
@@ -308,7 +308,7 @@ DSH 实机设置截图,随浅色 / 深色主题切换。
308
308
  <summary>终端方式</summary>
309
309
 
310
310
  ```sh
311
- dsh plugin --profile web update dsh-codex-subscription@3.1.3
311
+ dsh plugin --profile web update dsh-codex-subscription@3.1.4
312
312
  ```
313
313
 
314
314
  仅在需要卸载时运行:
package/lib/client.js CHANGED
@@ -995,7 +995,7 @@ window.__ModuleLoader__.load({
995
995
  const hasImage = (block) => block?.content?.some((part) => part.type === "image" && part.attachment);
996
996
  const isImage = (part) => part?.type === "image" && part.attachment;
997
997
  const resultsOf = (event) => {
998
- if (event?.type !== "tool/result" || event.data.meta?.kind !== "codex-subscription-image") return [];
998
+ if (event?.type !== "tool/result" || !["codex-subscription-image", "codex-subscription-sketch-finish"].includes(event.data.meta?.kind) || event.data.message?.isError) return [];
999
999
  const content = event.data.message?.content ?? [];
1000
1000
  const wrapped = content.filter((block) => block.type === "tool-result" && !block.isError && hasImage(block));
1001
1001
  if (wrapped.length > 0) return wrapped;
@@ -1258,6 +1258,7 @@ window.__ModuleLoader__.load({
1258
1258
  "voice/start",
1259
1259
  "voice/stop",
1260
1260
  "voice/status",
1261
+ "voice/interrupt",
1261
1262
  "voice/preview",
1262
1263
  "voice/catalog",
1263
1264
  "remote/status",
@@ -4001,7 +4002,7 @@ window.__ModuleLoader__.load({
4001
4002
  }
4002
4003
  if (request.revision === void 0) throw stale("revision is required: copy it from the last result");
4003
4004
  if (request.revision !== current.revision || adapter.busy()) throw stale("Sketch changed or is being edited; inspect again");
4004
- let changedObjects, progress, previousError;
4005
+ let changedObjects, progress, previousError, png, delivery;
4005
4006
  const report = {};
4006
4007
  const measureNow = async () => {
4007
4008
  try {
@@ -4051,7 +4052,13 @@ window.__ModuleLoader__.load({
4051
4052
  if (request.name !== void 0 && (typeof request.name !== "string" || request.name.length > 60)) throw Error("Invalid draft name");
4052
4053
  pending = true;
4053
4054
  try {
4055
+ if (request.finalPreview) png = await adapter.preview({ drawingOnly: true });
4054
4056
  await adapter.save(request.name);
4057
+ if (request.finalPreview) delivery = {
4058
+ status: "saved",
4059
+ documentId: current.documentId,
4060
+ revision: current.revision
4061
+ };
4055
4062
  } finally {
4056
4063
  pending = false;
4057
4064
  }
@@ -4071,7 +4078,11 @@ window.__ModuleLoader__.load({
4071
4078
  } : {},
4072
4079
  ...report?.warnings?.length ? { warnings: report.warnings } : {},
4073
4080
  ...report?.clampedPoints ? { clampedPoints: report.clampedPoints } : {},
4074
- ...progress ? { progress } : {}
4081
+ ...progress ? { progress } : {},
4082
+ ...png ? {
4083
+ png,
4084
+ delivery
4085
+ } : {}
4075
4086
  };
4076
4087
  completed.set(key, {
4077
4088
  fingerprint,
@@ -4082,10 +4093,10 @@ window.__ModuleLoader__.load({
4082
4093
  revision: result.revision
4083
4094
  }
4084
4095
  });
4085
- cachedCharacters += fingerprint.length;
4096
+ cachedCharacters += fingerprint.length + (png?.length ?? 0);
4086
4097
  while (completed.size > 1 && (completed.size > 128 || cachedCharacters > 4e6)) {
4087
4098
  const oldest = completed.keys().next().value;
4088
- cachedCharacters -= completed.get(oldest).fingerprint.length;
4099
+ cachedCharacters -= completed.get(oldest).fingerprint.length + (completed.get(oldest).result.png?.length ?? 0);
4089
4100
  completed.delete(oldest);
4090
4101
  }
4091
4102
  if (request.action === "apply" && request.look === true && typeof adapter.preview === "function") {
@@ -4691,7 +4702,7 @@ window.__ModuleLoader__.load({
4691
4702
  grid(context, surface.width, surface.height);
4692
4703
  return surface.toDataURL("image/png");
4693
4704
  }
4694
- const surface = render(doc);
4705
+ const surface = render(options.drawingOnly ? drawingOf(doc) : doc);
4695
4706
  grid(surface.getContext("2d"), surface.width, surface.height);
4696
4707
  return surface.toDataURL("image/png");
4697
4708
  }
@@ -5482,7 +5493,8 @@ window.__ModuleLoader__.load({
5482
5493
  }
5483
5494
  const value = await execute(request.action === "finish" ? {
5484
5495
  ...request,
5485
- action: "save"
5496
+ action: "save",
5497
+ finalPreview: true
5486
5498
  } : request);
5487
5499
  if (version !== generation) throw Error("Drawing interrupted");
5488
5500
  if (request.action !== "finish") return {
@@ -7322,6 +7334,7 @@ window.__ModuleLoader__.load({
7322
7334
  voiceLang_de: "Deutsch",
7323
7335
  voiceLang_pt: "Português",
7324
7336
  voiceLang_ru: "Русский",
7337
+ voicePreviewHint: "切换回答语言会播放该语言的试听;选择自动跟随时,试听使用英语。",
7325
7338
  remoteHint: "开启后,这台电脑上的 DSH 会出现在 ChatGPT 手机 App 的 Codex 主机列表里,可用手机查看对话、发消息、切换模型和审批。需要订阅账号登录;电脑要保持开机和联网。",
7326
7339
  remoteConnected: "电脑已连上 ChatGPT,还没有手机连接",
7327
7340
  remoteConnecting: "正在连接",
@@ -8165,6 +8178,7 @@ window.__ModuleLoader__.load({
8165
8178
  voiceLang_de: "Deutsch",
8166
8179
  voiceLang_pt: "Português",
8167
8180
  voiceLang_ru: "Русский",
8181
+ voicePreviewHint: "Changing the answer language plays a sample in that language. Auto uses an English sample.",
8168
8182
  remoteHint: "When on, this computer's DSH appears as a host in the ChatGPT mobile app's Codex list, so you can follow conversations, send messages, switch models and approve actions from your phone. Needs a signed-in subscription account; the computer must stay on and online.",
8169
8183
  remoteConnected: "This computer is online with ChatGPT; no phone connected yet",
8170
8184
  remoteConnecting: "Connecting",
@@ -11478,7 +11492,7 @@ window.__ModuleLoader__.load({
11478
11492
  }
11479
11493
  //#endregion
11480
11494
  //#region src/version.js
11481
- const PACKAGE_VERSION = "3.1.3";
11495
+ const PACKAGE_VERSION = "3.1.4";
11482
11496
  //#endregion
11483
11497
  //#region src/client-recovery.js
11484
11498
  async function recoveryCall(rpc, endpoint, payload = {}, timeoutMs = 1e4) {
@@ -12216,6 +12230,35 @@ window.__ModuleLoader__.load({
12216
12230
  });
12217
12231
  }
12218
12232
  //#endregion
12233
+ //#region src/voice-barge-in.js
12234
+ /** Mute playback promptly, and restore it only after interrupted audio has drained. */
12235
+ function createBargeInGate({ interrupt, changed, speechMs = 120, silenceMs = 400 }) {
12236
+ let speakingAt, quietAt, outputQuietAt, suppressed = false, drained = false;
12237
+ return { sample({ mic, output, now }) {
12238
+ if (mic > .12) {
12239
+ speakingAt ??= now;
12240
+ quietAt = void 0;
12241
+ } else {
12242
+ speakingAt = void 0;
12243
+ quietAt ??= now;
12244
+ }
12245
+ if (output < .025) outputQuietAt ??= now;
12246
+ else outputQuietAt = void 0;
12247
+ if (!suppressed && speakingAt !== void 0 && now - speakingAt >= speechMs && output > .025) {
12248
+ suppressed = true;
12249
+ drained = false;
12250
+ changed(true);
12251
+ interrupt();
12252
+ }
12253
+ if (suppressed && outputQuietAt !== void 0 && now - outputQuietAt >= 250) drained = true;
12254
+ if (suppressed && drained && quietAt !== void 0 && now - quietAt >= silenceMs) {
12255
+ suppressed = false;
12256
+ speakingAt = void 0;
12257
+ changed(false);
12258
+ }
12259
+ } };
12260
+ }
12261
+ //#endregion
12219
12262
  //#region src/voice-call.js
12220
12263
  const ICE_WAIT_MS = 3e3;
12221
12264
  const waitForCandidates = (connection) => new Promise((resolve) => {
@@ -12302,9 +12345,11 @@ window.__ModuleLoader__.load({
12302
12345
  for (const track of stream.getTracks()) connection.addTrack(track, stream);
12303
12346
  connection.createDataChannel("oai-events");
12304
12347
  let ended = false;
12348
+ let monitor;
12305
12349
  const end = async () => {
12306
12350
  if (ended) return;
12307
12351
  ended = true;
12352
+ clearInterval(monitor);
12308
12353
  if (context) chime(context, [740, 520]);
12309
12354
  for (const track of stream.getTracks()) track.stop();
12310
12355
  sound.srcObject = null;
@@ -12354,6 +12399,22 @@ window.__ModuleLoader__.load({
12354
12399
  assistant: /* @__PURE__ */ new Uint8Array(512)
12355
12400
  };
12356
12401
  let muted = false;
12402
+ let outputMuted = false;
12403
+ let interrupted = false;
12404
+ const gate = createBargeInGate({
12405
+ changed: (value) => {
12406
+ interrupted = value;
12407
+ sound.muted = outputMuted || interrupted;
12408
+ },
12409
+ interrupt: () => {
12410
+ rpc.call(CHANNEL, "voice/interrupt", { sessionId }).catch(() => {});
12411
+ }
12412
+ });
12413
+ if (context) monitor = setInterval(() => gate.sample({
12414
+ mic: muted ? 0 : loudness(analysers.mic, buffers.mic),
12415
+ output: loudness(analysers.assistant, buffers.assistant),
12416
+ now: performance.now()
12417
+ }), 30);
12357
12418
  return {
12358
12419
  stop: end,
12359
12420
  isMuted: () => muted,
@@ -12361,9 +12422,10 @@ window.__ModuleLoader__.load({
12361
12422
  muted = value;
12362
12423
  for (const track of stream.getAudioTracks()) track.enabled = !value;
12363
12424
  },
12364
- isOutputMuted: () => sound.muted,
12425
+ isOutputMuted: () => outputMuted,
12365
12426
  setOutputMuted: (value) => {
12366
- sound.muted = value;
12427
+ outputMuted = value;
12428
+ sound.muted = outputMuted || interrupted;
12367
12429
  },
12368
12430
  /** How loud the person (mic) and the model (voice) are right now, 0..1 each. */
12369
12431
  levels: () => ({
@@ -13253,6 +13315,7 @@ void main(){
13253
13315
  /** Settings for the composer's voice button: on or off, the voice (with a short sample to listen to) and the answer language. */
13254
13316
  function VoiceCallCard({ rpc, preference, snapshot, t }) {
13255
13317
  const audio = (0, react.useRef)();
13318
+ const previewSequence = (0, react.useRef)(0);
13256
13319
  const alive = (0, react.useRef)(false);
13257
13320
  const [offered, setOffered] = (0, react.useState)();
13258
13321
  const [sample, setSample] = (0, react.useState)({
@@ -13277,15 +13340,19 @@ void main(){
13277
13340
  })();
13278
13341
  }, [on]);
13279
13342
  /** Play a short clip of a voice; picking a voice plays it too, so it can be heard before it is used. */
13280
- const playVoice = async (voice) => {
13343
+ const playVoice = async (voice, language = snapshot.voiceLanguage) => {
13344
+ const sequence = ++previewSequence.current;
13281
13345
  audio.current?.pause();
13282
13346
  setSample({
13283
13347
  state: "loading",
13284
13348
  note: ""
13285
13349
  });
13286
13350
  try {
13287
- const result = await rpc.call(CHANNEL, "voice/preview", { voice });
13288
- if (!alive.current) return;
13351
+ const result = await rpc.call(CHANNEL, "voice/preview", {
13352
+ voice,
13353
+ language
13354
+ });
13355
+ if (!alive.current || sequence !== previewSequence.current) return;
13289
13356
  if (!result.ok) {
13290
13357
  setSample({
13291
13358
  state: "missing",
@@ -13296,7 +13363,7 @@ void main(){
13296
13363
  const clip = new Audio(result.value.audio);
13297
13364
  audio.current = clip;
13298
13365
  clip.onended = () => {
13299
- if (alive.current) setSample((current) => ({
13366
+ if (alive.current && sequence === previewSequence.current) setSample((current) => ({
13300
13367
  ...current,
13301
13368
  state: "idle"
13302
13369
  }));
@@ -13307,7 +13374,7 @@ void main(){
13307
13374
  });
13308
13375
  await clip.play();
13309
13376
  } catch {
13310
- if (alive.current) setSample({
13377
+ if (alive.current && sequence === previewSequence.current) setSample({
13311
13378
  state: "missing",
13312
13379
  note: ""
13313
13380
  });
@@ -13398,7 +13465,12 @@ void main(){
13398
13465
  items: languages,
13399
13466
  onSelect: (value) => {
13400
13467
  preference.set({ [VOICE_LANGUAGE_FIELD]: value });
13468
+ playVoice(snapshot.voiceVoice, value);
13401
13469
  }
13470
+ }),
13471
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
13472
+ className: "codexSubscriptionHelp",
13473
+ children: t("voicePreviewHint")
13402
13474
  })
13403
13475
  ] }) : null]
13404
13476
  });
package/lib/index.js CHANGED
@@ -1464,6 +1464,7 @@ const RPC_ENDPOINTS = Object.freeze([
1464
1464
  "voice/start",
1465
1465
  "voice/stop",
1466
1466
  "voice/status",
1467
+ "voice/interrupt",
1467
1468
  "voice/preview",
1468
1469
  "voice/catalog",
1469
1470
  "remote/status",
@@ -2485,7 +2486,7 @@ function inheritedOriginalImageRef(session, assetId) {
2485
2486
  }
2486
2487
  //#endregion
2487
2488
  //#region src/version.js
2488
- const PACKAGE_VERSION = "3.1.3";
2489
+ const PACKAGE_VERSION = "3.1.4";
2489
2490
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
2490
2491
  //#endregion
2491
2492
  //#region src/http-failure.js
@@ -3092,7 +3093,7 @@ const MAX_REFERENCE_BYTES = 14e5;
3092
3093
  function createSketchAgentTool(bridge, attachments, getSessionMessages = () => []) {
3093
3094
  return defineTool({
3094
3095
  name: "codex_sketch",
3095
- description: "Edit the sketch board in this session using native editable strokes and layers. Use for @sketch requests and explicit follow-up edits to that drawing. The toolbar pen button is for manual drawing; do not require the user to open it. Start with inspect for the runId, documentId, revision and command reference. Draw with the svg op whenever possible: one SVG document per stage (paths, shapes, groups, transforms; see the reference from inspect) is far faster and richer than hand-placed strokes, and still becomes native editable strokes. Draw with depth, not flat colour: skies, skin, metal and glass take real linear/radial gradients (fill=\"url(#id)\"), glows, shadows, haze and distant things take a feGaussianBlur filter (soft edge), and light comes from a consistent direction with a darker shade, a lighter highlight and a reflected-light edge on each form. Draw the shapes, hair, clothing and lettering outlines of every layer with svg; use stroke commands only for small corrections and native text. Apply atomic batches and preview between stages. When the user attached a reference image, call reference with its attachmentId once after inspect to put it on the board as a hidden picture layer. To reproduce a reference faithfully, draw it yourself in stages, from big to small: 1) write a short plan (parts, drawing order, rough position and size of each), using preview with grid and measure with palette and regions to read proportions, key positions and the main colours, and measure scan along a few rows and columns to find exact edges; 2) block in the silhouette and the big colour areas (hair, clothes, skin, background) as filled shapes; 3) after every apply read progress (error, previous error, worst cells) and use preview mode side or diff, with box to zoom into a part, to see what is off; 4) fix the worst area first (position and size before colour, colour before detail), 5) then shading, then outlines and small details (eyes, headphones, patterns). Read exact colours from the reference with measure points instead of guessing. If a stage raised the error or looks wrong, undo it instead of painting over it. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft. Stop when every part has had its pass and the error stops improving. When a reference picture is on the board, keep its layer hidden while drawing (compare shows it anyway), measure its key positions with preview grid, draw big shapes first, and after each stage check preview compare and fix the largest offset before adding detail. For repeated details such as hair strands or lace, generate the SVG with a script instead of placing each one by hand. and call finish to save the finished draft and release the editing lock. save is only a checkpoint. Closing the board does not stop drawing. If the user stops drawing, do not retry. Never generates AI images, sends messages or attaches images automatically. Inspect automatically opens the board in the currently viewed session. Do not ask the user to open it first. If the session is not visible in DSH, ask them to switch to it. On timeout inspect before retrying; reuse the exact requestId only for the same request.",
3096
+ description: "Edit the sketch board in this session using native editable strokes and layers. Use for @sketch requests and explicit follow-up edits to that drawing. The toolbar pen button is for manual drawing; do not require the user to open it. Start with inspect for the runId, documentId, revision and command reference. Draw with the svg op whenever possible: one SVG document per stage (paths, shapes, groups, transforms; see the reference from inspect) is far faster and richer than hand-placed strokes, and still becomes native editable strokes. Draw with depth, not flat colour: skies, skin, metal and glass take real linear/radial gradients (fill=\"url(#id)\"), glows, shadows, haze and distant things take a feGaussianBlur filter (soft edge), and light comes from a consistent direction with a darker shade, a lighter highlight and a reflected-light edge on each form. Draw the shapes, hair, clothing and lettering outlines of every layer with svg; use stroke commands only for small corrections and native text. Apply atomic batches and preview between stages. When the user attached a reference image, call reference with its attachmentId once after inspect to put it on the board as a hidden picture layer. To reproduce a reference faithfully, draw it yourself in stages, from big to small: 1) write a short plan (parts, drawing order, rough position and size of each), using preview with grid and measure with palette and regions to read proportions, key positions and the main colours, and measure scan along a few rows and columns to find exact edges; 2) block in the silhouette and the big colour areas (hair, clothes, skin, background) as filled shapes; 3) after every apply read progress (error, previous error, worst cells) and use preview mode side or diff, with box to zoom into a part, to see what is off; 4) fix the worst area first (position and size before colour, colour before detail), 5) then shading, then outlines and small details (eyes, headphones, patterns). Read exact colours from the reference with measure points instead of guessing. If a stage raised the error or looks wrong, undo it instead of painting over it. When the whole picture is roughly right, do refinement passes region by region instead of stopping: split the picture into its parts (for a figure: head and face, each mass of hair, torso, each arm, each leg, shoes and small accessories). For every part, call preview mode side with box set to that part and grid on (zoomed up to 3x) and look at reference and drawing next to each other, then measure with box on the same part and use scan along an edge to read exact positions; list the three biggest differences (edge position, size, colour, missing detail), fix them with targeted object updates or a replacement shape, and check progress. A part is done when its error stops falling or the zoomed pair looks the same; then go to the next part. Make at least one pass over every part before you finish, and never end with the first full draft. Stop when every part has had its pass and the error stops improving. When a reference picture is on the board, keep its layer hidden while drawing (compare shows it anyway), measure its key positions with preview grid, draw big shapes first, and after each stage check preview compare and fix the largest offset before adding detail. For repeated details such as hair strands or lace, generate the SVG with a script instead of placing each one by hand. and call finish to save the finished draft and release the editing lock. save is only a checkpoint. Closing the board does not stop drawing. If the user stops drawing, do not retry. Never generates AI images or sends messages. Finish returns the saved drawing as a native image attachment displayed by DSH. Refer to that attachment; never invent a Markdown image URL or use a shell-output/log path as an image. Inspect automatically opens the board in the currently viewed session. Do not ask the user to open it first. If the session is not visible in DSH, ask them to switch to it. On timeout inspect before retrying; reuse the exact requestId only for the same request.",
3096
3097
  parameters: {
3097
3098
  action: {
3098
3099
  type: "string",
@@ -3274,17 +3275,34 @@ function createSketchAgentTool(bridge, attachments, getSessionMessages = () => [
3274
3275
  request.name = image.name ?? "reference";
3275
3276
  }
3276
3277
  const value = await bridge.request(sessionId, request, exec.signal);
3278
+ if (args.action === "finish" && !value.png) throw Error("The board returned no final image. Reload DSH to load the current sketch client, then inspect the saved drawing before retrying.");
3277
3279
  if (value.png) {
3278
3280
  if (!/^data:image\/png;base64,/.test(value.png) || value.png.length > 8 * 1024 * 1024) throw Error("Invalid sketch preview");
3281
+ const data = Buffer.from(value.png.split(",")[1], "base64");
3282
+ if (!data.subarray(0, 8).equals(Buffer.from([
3283
+ 137,
3284
+ 80,
3285
+ 78,
3286
+ 71,
3287
+ 13,
3288
+ 10,
3289
+ 26,
3290
+ 10
3291
+ ]))) throw Error("Invalid sketch preview: expected PNG bytes");
3279
3292
  const image = await attachments.saveImage({
3280
- data: new Uint8Array(Buffer.from(value.png.split(",")[1], "base64")),
3293
+ data: new Uint8Array(data),
3281
3294
  mediaType: "image/png",
3282
- name: "sketch-preview.png"
3295
+ name: args.action === "finish" ? "sketch-finished.png" : "sketch-preview.png"
3283
3296
  });
3284
3297
  const { png, ...snapshot } = value;
3285
3298
  return {
3286
3299
  ...snapshot,
3287
- image
3300
+ image,
3301
+ ...args.action === "finish" ? { delivery: {
3302
+ ...value.delivery,
3303
+ image,
3304
+ note: "The saved drawing is attached and displayed by DSH. Refer to the attached image directly; never use a shell-output/log path as an image."
3305
+ } } : {}
3288
3306
  };
3289
3307
  }
3290
3308
  return value;
@@ -3294,6 +3312,11 @@ function createSketchAgentTool(bridge, attachments, getSessionMessages = () => [
3294
3312
  type: "object",
3295
3313
  additionalProperties: true
3296
3314
  },
3315
+ presentationMeta: (args, value) => ({
3316
+ kind: args.action === "finish" && value.image ? "codex-subscription-sketch-finish" : "codex-subscription-sketch",
3317
+ documentId: value.documentId,
3318
+ revision: value.revision
3319
+ }),
3297
3320
  render: (_args, value) => [{
3298
3321
  type: "text",
3299
3322
  text: JSON.stringify({
@@ -4256,7 +4279,7 @@ function gitArguments(command) {
4256
4279
  const [subcommand, ...args] = rest;
4257
4280
  if (subcommand === void 0) return { error: "no git subcommand" };
4258
4281
  if (args.some((arg) => FORBIDDEN.test(arg))) return { error: `option not allowed with git ${subcommand}` };
4259
- const exact = EXACT.some((form) => form.length === rest.length && form.every((part, index) => part === rest[index]));
4282
+ const exact = EXACT.some((form) => form.length === rest.length && form.every((part, index) => part === rest[index])) || subcommand === "symbolic-ref" && args.length === 2 && args[0] === "--short" && /^refs\/remotes\/[^\0\r\n]+\/HEAD$/u.test(args[1]);
4260
4283
  if (!READ_ONLY.has(subcommand) && !exact) return { error: `git ${subcommand} is not available` };
4261
4284
  return { argv: [
4262
4285
  "-c",
@@ -4272,8 +4295,12 @@ function gitArguments(command) {
4272
4295
  ] };
4273
4296
  }
4274
4297
  const inside = (folder, root) => {
4275
- const path = relative(resolve(root), resolve(folder));
4276
- return path === "" || !path.startsWith("..") && !path.startsWith(`..${sep}`) && !/^[A-Za-z]:/u.test(path);
4298
+ try {
4299
+ const path = relative(realpathSync.native(root), folder);
4300
+ return path === "" || path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
4301
+ } catch {
4302
+ return false;
4303
+ }
4277
4304
  };
4278
4305
  /**
4279
4306
  * @param {{ command: string[], cwd?: string, timeoutMs?: number, outputBytesCap?: number, tty?: boolean, streamStdin?: boolean, streamStdoutStderr?: boolean }} params
@@ -4283,12 +4310,18 @@ function runGit(params, { folders, run = execFile }) {
4283
4310
  const parsed = gitArguments(params?.command);
4284
4311
  if (parsed.error) return Promise.reject(Object.assign(new Error(parsed.error), { code: "not-allowed" }));
4285
4312
  if (params.tty || params.streamStdin || params.streamStdoutStderr) return Promise.reject(Object.assign(/* @__PURE__ */ new Error("streaming is not available"), { code: "not-allowed" }));
4286
- const cwd = localFolder(params.cwd);
4313
+ let cwd = localFolder(params.cwd);
4314
+ try {
4315
+ cwd = cwd && realpathSync.native(cwd);
4316
+ } catch {
4317
+ cwd = void 0;
4318
+ }
4287
4319
  if (!cwd || !folders.some((root) => inside(cwd, root))) return Promise.reject(Object.assign(/* @__PURE__ */ new Error("git only runs in a DSH conversation folder"), { code: "not-allowed" }));
4288
4320
  const timeout = Math.min(Number.isFinite(params.timeoutMs) && params.timeoutMs > 0 ? params.timeoutMs : DEFAULT_TIMEOUT_MS$2, MAX_TIMEOUT_MS);
4289
4321
  const cap = Math.min(Number.isInteger(params.outputBytesCap) && params.outputBytesCap > 0 ? params.outputBytesCap : DEFAULT_OUTPUT_BYTES, MAX_OUTPUT_BYTES);
4290
4322
  const env = {
4291
4323
  ...process.env,
4324
+ GIT_LITERAL_PATHSPECS: "1",
4292
4325
  GIT_OPTIONAL_LOCKS: "0",
4293
4326
  GIT_TERMINAL_PROMPT: "0",
4294
4327
  GIT_PAGER: "cat",
@@ -4314,6 +4347,218 @@ function runGit(params, { folders, run = execFile }) {
4314
4347
  });
4315
4348
  }
4316
4349
  //#endregion
4350
+ //#region src/remote-control-git-probes.js
4351
+ const BRANCHES = "14c4c9e1481287733dd399473326c75c648339069226c3cfecdbabe7d7d87934";
4352
+ const DIFF = "ae570abfe66a30a882028df76ef000b1ed543cbf5e4c9d24e49a4d434a58cbe6";
4353
+ const WRAPPER = [
4354
+ "/bin/bash",
4355
+ "--noprofile",
4356
+ "--norc",
4357
+ "-p",
4358
+ "-c",
4359
+ "printf '\\0'; exec \"$@\"",
4360
+ "codex-workspace-diff",
4361
+ "/bin/bash",
4362
+ "-lc"
4363
+ ];
4364
+ const probeDigest = (value) => typeof value === "string" ? createHash("sha256").update(value).digest("hex") : "";
4365
+ const denied = (message) => Object.assign(new Error(message), { code: "not-allowed" });
4366
+ const lines$1 = (value) => value.trim().split("\n").filter(Boolean);
4367
+ const encoded = (label, value) => `${label}\0${Buffer.from(value).toString("base64")}\0`;
4368
+ /** Returns undefined for every command other than the two captured phone probes. */
4369
+ function phoneGitProbe(command) {
4370
+ if (!Array.isArray(command)) return void 0;
4371
+ if (command.length === 3 && command[0] === "/bin/sh" && command[1] === "-lc" && probeDigest(command[2]) === BRANCHES) return { kind: "branches" };
4372
+ if (command.length !== 18 || !WRAPPER.every((part, index) => command[index] === part) || probeDigest(command[9]) !== DIFF || command[10] !== "codex-workspace-diff") return void 0;
4373
+ const [ref, source, required, remote, contents, perFile, total] = command.slice(11);
4374
+ if (typeof ref !== "string" || ref.length > 1024 || ref.startsWith("-") || /[\0\r\n]/u.test(ref) || ![
4375
+ "branch",
4376
+ "staged",
4377
+ "unstaged"
4378
+ ].includes(source)) return void 0;
4379
+ if (![
4380
+ required,
4381
+ remote,
4382
+ contents
4383
+ ].every((value) => value === "true" || value === "false") || ![perFile, total].every((value) => typeof value === "string" && /^\d{1,7}$/u.test(value))) return void 0;
4384
+ return {
4385
+ kind: "diff",
4386
+ ref,
4387
+ source,
4388
+ required: required === "true",
4389
+ contents: contents === "true",
4390
+ perFile: Number(perFile),
4391
+ total: Number(total)
4392
+ };
4393
+ }
4394
+ async function runPhoneGitProbe(params, { folders, notify, signal } = {}) {
4395
+ const probe = phoneGitProbe(params?.command);
4396
+ if (!probe) throw denied("unknown phone git probe");
4397
+ if (params.tty || params.streamStdin || params.streamStdoutStderr && (typeof params.processId !== "string" || !params.processId)) throw denied("unsupported phone git stream");
4398
+ const deadline = Date.now() + Math.min(params.timeoutMs > 0 ? params.timeoutMs : 15e3, 3e4);
4399
+ const cap = Math.min(Number.isInteger(params.outputBytesCap) && params.outputBytesCap > 0 ? params.outputBytesCap : 1024 * 1024, 4 * 1024 * 1024);
4400
+ const git = async (...args) => {
4401
+ signal?.throwIfAborted();
4402
+ if (Date.now() >= deadline) throw new Error("phone git query timed out");
4403
+ return runGit({
4404
+ command: ["git", ...args],
4405
+ cwd: params.cwd,
4406
+ timeoutMs: deadline - Date.now(),
4407
+ outputBytesCap: cap
4408
+ }, { folders });
4409
+ };
4410
+ const read = async (...args) => {
4411
+ const result = await git(...args);
4412
+ if (result.exitCode !== 0) throw new Error(result.stderr || "git query failed");
4413
+ return result.stdout;
4414
+ };
4415
+ const exists = async (ref) => (await git("rev-parse", "--verify", "--quiet", ref)).exitCode === 0;
4416
+ const localDefault = async () => {
4417
+ if (await exists("refs/heads/main")) return "main";
4418
+ if (await exists("refs/heads/master")) return "master";
4419
+ return "";
4420
+ };
4421
+ let stdout;
4422
+ if (probe.kind === "branches") {
4423
+ const current = (await read("branch", "--show-current")).trim();
4424
+ const remote = await git("symbolic-ref", "--short", "refs/remotes/origin/HEAD");
4425
+ const ref = remote.exitCode === 0 ? remote.stdout.trim() : await localDefault();
4426
+ const preferred = ref.replace(/^origin\//u, "");
4427
+ const first = preferred && await exists(`refs/heads/${preferred}`) ? preferred : await localDefault();
4428
+ const recent = lines$1(await read("for-each-ref", "--sort=-committerdate", "--format=%(refname:short)", "refs/heads"));
4429
+ const label = (name) => {
4430
+ const value = params.env?.[`CODEX_DRAFT_OUTPUT_${name}`];
4431
+ if (typeof value !== "string" || value.length > 100 || /[\0\r\n\t]/u.test(value)) throw denied("invalid branch output label");
4432
+ return value;
4433
+ };
4434
+ stdout = `${label("CURRENT")}\t${current}\n${label("DEFAULT")}\t${ref}\n` + [first, ...recent.filter((branch) => branch !== first)].filter(Boolean).slice(0, 8).map((branch) => `${label("BRANCH")}\t${branch}\n`).join("");
4435
+ } else {
4436
+ const root = await git("rev-parse", "--show-toplevel");
4437
+ if (root.exitCode !== 0) stdout = "\0notGitRepository\0";
4438
+ else {
4439
+ const cwd = root.stdout.trim();
4440
+ params = {
4441
+ ...params,
4442
+ cwd
4443
+ };
4444
+ await git("rev-parse", "--show-toplevel");
4445
+ let base = [], comparison = "", failure = "";
4446
+ stdout = `\0git\0${cwd}\0`;
4447
+ if (probe.source === "branch") {
4448
+ if (await exists("HEAD")) {
4449
+ const remotes = lines$1(await read("remote")).sort((a, b) => Number(b === "origin") - Number(a === "origin"));
4450
+ if (probe.required) comparison = probe.ref && await exists(`${probe.ref}^{commit}`) ? probe.ref : "";
4451
+ else {
4452
+ for (const remote of remotes) {
4453
+ const symbolic = await git("symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`);
4454
+ const candidates = [
4455
+ symbolic.exitCode === 0 ? symbolic.stdout.trim() : "",
4456
+ probe.ref.startsWith(`${remote}/`) ? probe.ref : "",
4457
+ `${remote}/main`,
4458
+ `${remote}/master`
4459
+ ];
4460
+ for (const ref of candidates.filter(Boolean)) if (await exists(`refs/remotes/${ref}`)) {
4461
+ comparison = ref;
4462
+ break;
4463
+ }
4464
+ if (comparison) break;
4465
+ }
4466
+ if (!comparison && probe.ref && await exists(`${probe.ref}^{commit}`)) comparison = probe.ref;
4467
+ }
4468
+ const merge = comparison ? await git("merge-base", "HEAD", comparison) : void 0;
4469
+ if (probe.required && !comparison) failure = "comparisonBranchUnavailable";
4470
+ else if (probe.required && merge?.exitCode !== 0) failure = "comparisonBranchDoesNotShareHistory";
4471
+ base = [merge?.exitCode === 0 ? merge.stdout.trim() : "HEAD"];
4472
+ } else base = ["4b825dc642cb6eb9a060e54bf8d69288fbee4904"];
4473
+ stdout += `currentBranch\0${(await git("symbolic-ref", "--short", "HEAD")).stdout.trim()}\0` + lines$1(await read("for-each-ref", "--count=8", "--sort=-committerdate", "--format=%(refname:short)", "refs/heads")).map((branch) => `recentBranch\0${branch}\0`).join("");
4474
+ if (comparison) stdout += `comparisonRef\0${comparison}\0`;
4475
+ } else if (probe.source === "staged") base = ["--cached"];
4476
+ if (failure) stdout = "\0" + encoded("commandFailed", failure);
4477
+ else {
4478
+ const parts = [{
4479
+ stats: await read("diff", "--find-renames", "--numstat", "-z", ...base, "--"),
4480
+ base
4481
+ }];
4482
+ if (probe.source !== "staged") for (const file of (await read("ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean)) {
4483
+ if (!(await lstat(join(cwd, file))).isFile()) continue;
4484
+ const result = await git("diff", "--no-index", "--numstat", "-z", "--", "/dev/null", file);
4485
+ if (result.exitCode > 1) throw new Error(result.stderr || "git query failed");
4486
+ parts.push({
4487
+ stats: result.stdout.replace(/\t\0\/dev\/null\0/u, " "),
4488
+ file
4489
+ });
4490
+ }
4491
+ stdout += encoded("trackedNumstat", parts.map((part) => part.stats).join(""));
4492
+ if (probe.contents) {
4493
+ let changed = 0;
4494
+ const selected = parts.map((part) => {
4495
+ const paths = [], entries = part.stats.split("\0");
4496
+ for (let index = 0; index < entries.length; index++) {
4497
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/u.exec(entries[index]);
4498
+ if (!match) continue;
4499
+ const names = match[3] ? [match[3]] : [entries[++index], entries[++index]];
4500
+ const count = (Number(match[1]) || 0) + (Number(match[2]) || 0);
4501
+ if (count > 0 && count <= probe.perFile) {
4502
+ changed += count;
4503
+ paths.push(...names);
4504
+ }
4505
+ }
4506
+ return {
4507
+ ...part,
4508
+ paths
4509
+ };
4510
+ });
4511
+ if (changed <= probe.total) {
4512
+ let diff = "";
4513
+ for (const part of selected.filter((part) => part.paths.length)) {
4514
+ const result = await git(...[
4515
+ "diff",
4516
+ "--find-renames",
4517
+ "--src-prefix=a/",
4518
+ "--dst-prefix=b/",
4519
+ "--unified=2",
4520
+ ...part.file ? [
4521
+ "--no-index",
4522
+ "--",
4523
+ "/dev/null",
4524
+ part.file
4525
+ ] : [
4526
+ ...part.base,
4527
+ "--",
4528
+ ...part.paths
4529
+ ]
4530
+ ]);
4531
+ if (result.exitCode > (part.file ? 1 : 0)) throw new Error(result.stderr || "git query failed");
4532
+ diff += result.stdout;
4533
+ }
4534
+ if (diff) stdout += encoded("trackedDiff", diff);
4535
+ }
4536
+ }
4537
+ }
4538
+ }
4539
+ }
4540
+ const bytes = Buffer.from(stdout);
4541
+ if (bytes.length > cap) throw new Error("phone git output exceeds the requested limit");
4542
+ if (params.streamStdoutStderr) {
4543
+ await notify("command/exec/outputDelta", {
4544
+ processId: params.processId,
4545
+ stream: "stdout",
4546
+ deltaBase64: bytes.toString("base64"),
4547
+ capReached: false
4548
+ });
4549
+ return {
4550
+ exitCode: 0,
4551
+ stdout: "",
4552
+ stderr: ""
4553
+ };
4554
+ }
4555
+ return {
4556
+ exitCode: 0,
4557
+ stdout,
4558
+ stderr: ""
4559
+ };
4560
+ }
4561
+ //#endregion
4317
4562
  //#region src/remote-control-files.js
4318
4563
  const SKIP = /* @__PURE__ */ new Set([
4319
4564
  "node_modules",
@@ -4402,6 +4647,231 @@ async function searchFiles({ roots, query, folders, now = Date.now }) {
4402
4647
  return found.sort((a, b) => b.score - a.score || a.path.length - b.path.length).slice(0, RESULTS);
4403
4648
  }
4404
4649
  //#endregion
4650
+ //#region src/voice-questions.js
4651
+ const normal = (value) => String(value).normalize("NFKC").toLocaleLowerCase().replaceAll("個", "个").replaceAll("項", "项").replaceAll("號", "号").replace(/[\s\p{P}\p{S}]/gu, "");
4652
+ const ordinals = [
4653
+ [
4654
+ "1",
4655
+ "一",
4656
+ "壹",
4657
+ "first",
4658
+ "one",
4659
+ "いち",
4660
+ "ひとつめ",
4661
+ "첫번째",
4662
+ "하나",
4663
+ "primero",
4664
+ "premier",
4665
+ "erste",
4666
+ "primeiro",
4667
+ "первый"
4668
+ ],
4669
+ [
4670
+ "2",
4671
+ "二",
4672
+ "两",
4673
+ "second",
4674
+ "two",
4675
+ "に",
4676
+ "ふたつめ",
4677
+ "두번째",
4678
+ "둘",
4679
+ "segundo",
4680
+ "deuxième",
4681
+ "zweite",
4682
+ "второй"
4683
+ ],
4684
+ [
4685
+ "3",
4686
+ "三",
4687
+ "third",
4688
+ "three",
4689
+ "さん",
4690
+ "みっつめ",
4691
+ "세번째",
4692
+ "셋",
4693
+ "tercero",
4694
+ "troisième",
4695
+ "dritte",
4696
+ "terceiro",
4697
+ "третий"
4698
+ ],
4699
+ [
4700
+ "4",
4701
+ "四",
4702
+ "fourth",
4703
+ "four",
4704
+ "よん",
4705
+ "네번째",
4706
+ "cuarto",
4707
+ "quatrième",
4708
+ "vierte",
4709
+ "quarto",
4710
+ "четвертый"
4711
+ ],
4712
+ [
4713
+ "5",
4714
+ "五",
4715
+ "fifth",
4716
+ "five",
4717
+ "ご",
4718
+ "다섯번째",
4719
+ "quinto",
4720
+ "cinquième",
4721
+ "fünfte",
4722
+ "пятый"
4723
+ ],
4724
+ [
4725
+ "6",
4726
+ "六",
4727
+ "sixth",
4728
+ "six",
4729
+ "ろく",
4730
+ "여섯번째",
4731
+ "sexto",
4732
+ "sixième",
4733
+ "sechste",
4734
+ "шестой"
4735
+ ],
4736
+ [
4737
+ "7",
4738
+ "七",
4739
+ "seventh",
4740
+ "seven",
4741
+ "なな",
4742
+ "일곱번째",
4743
+ "séptimo",
4744
+ "septième",
4745
+ "siebte",
4746
+ "sétimo",
4747
+ "седьмой"
4748
+ ],
4749
+ [
4750
+ "8",
4751
+ "八",
4752
+ "eighth",
4753
+ "eight",
4754
+ "はち",
4755
+ "여덟번째",
4756
+ "octavo",
4757
+ "huitième",
4758
+ "achte",
4759
+ "oitavo",
4760
+ "восьмой"
4761
+ ],
4762
+ [
4763
+ "9",
4764
+ "九",
4765
+ "ninth",
4766
+ "nine",
4767
+ "きゅう",
4768
+ "아홉번째",
4769
+ "noveno",
4770
+ "neuvième",
4771
+ "neunte",
4772
+ "nono",
4773
+ "девятый"
4774
+ ]
4775
+ ];
4776
+ /** Match an explicit label or ordinal; ambiguous speech leaves the question open. */
4777
+ function spokenChoice(text, question) {
4778
+ const said = normal(text);
4779
+ const options = question.options ?? [];
4780
+ const exact = options.filter((option) => normal(option.label) === said);
4781
+ if (exact.length === 1) return {
4782
+ id: question.id,
4783
+ selected: [exact[0].label]
4784
+ };
4785
+ const ordinal = said.replace(/^(?:我选|我要选|选择|选|第|option|choose|ichoose|number|the|el|le|die|opção|вариант)/u, "").replace(/^(?:第|option|number|the)/u, "").replace(/(?:个|项|号|番目|番|の選択肢|option|please|です|にして|でお願いします)$/u, "");
4786
+ const index = ordinals.findIndex((words) => words.some((word) => normal(word) === ordinal));
4787
+ if (index >= 0 && options.length) return index < options.length ? {
4788
+ id: question.id,
4789
+ selected: [options[index].label]
4790
+ } : void 0;
4791
+ if (options.length === 0 && String(text).trim()) return {
4792
+ id: question.id,
4793
+ selected: [],
4794
+ custom: String(text).trim()
4795
+ };
4796
+ const custom = /^(?:其他[::,,\s]*|其它[::,,\s]*|other[::,,\s]+)(.+)$/iu.exec(String(text).trim());
4797
+ if (custom) return {
4798
+ id: question.id,
4799
+ selected: [],
4800
+ custom: custom[1].trim()
4801
+ };
4802
+ }
4803
+ function createVoiceQuestions({ speak, now = Date.now }) {
4804
+ let pending;
4805
+ let recent = [];
4806
+ const finish = (value, error) => {
4807
+ const current = pending;
4808
+ if (!current) return;
4809
+ pending = void 0;
4810
+ current.signal?.removeEventListener("abort", current.abort);
4811
+ if (error) current.reject(error);
4812
+ else current.resolve(value);
4813
+ };
4814
+ const prompt = () => {
4815
+ const question = pending.questions[pending.answers.length];
4816
+ speak(`[COMPLETE] Ask the user this question in the conversation's language and read every option with its number, then wait. A spoken option number or label is handled by the application; do not delegate it as a new task. Question: ${JSON.stringify({
4817
+ question: question.question,
4818
+ detail: question.detail,
4819
+ options: question.options?.map((option, index) => ({
4820
+ number: index + 1,
4821
+ label: option.label,
4822
+ description: option.description
4823
+ }))
4824
+ })}`);
4825
+ };
4826
+ return {
4827
+ ask(request) {
4828
+ if (pending) return Promise.reject(/* @__PURE__ */ new Error("Another voice question is still open"));
4829
+ if (request.signal?.aborted) return Promise.reject(request.signal.reason ?? /* @__PURE__ */ new Error("Question aborted"));
4830
+ return new Promise((resolve, reject) => {
4831
+ pending = {
4832
+ questions: request.questions,
4833
+ answers: [],
4834
+ signal: request.signal,
4835
+ resolve,
4836
+ reject
4837
+ };
4838
+ pending.abort = () => finish(void 0, request.signal.reason ?? /* @__PURE__ */ new Error("Question aborted"));
4839
+ request.signal?.addEventListener("abort", pending.abort, { once: true });
4840
+ prompt();
4841
+ });
4842
+ },
4843
+ consume(text, { delegation = false } = {}) {
4844
+ recent = recent.filter((item) => now() - item.at < 1e4);
4845
+ const echo = recent.find((item) => item.text === normal(text) && (delegation || item.delegation));
4846
+ if (echo) {
4847
+ if (!delegation) recent = recent.filter((item) => item !== echo);
4848
+ return true;
4849
+ }
4850
+ if (!pending) return false;
4851
+ const answer = spokenChoice(text, pending.questions[pending.answers.length]);
4852
+ if (!answer) {
4853
+ prompt();
4854
+ return true;
4855
+ }
4856
+ recent.push({
4857
+ text: normal(text),
4858
+ at: now(),
4859
+ delegation
4860
+ });
4861
+ pending.answers.push(answer);
4862
+ if (pending.answers.length === pending.questions.length) finish({ answers: pending.answers });
4863
+ else prompt();
4864
+ return true;
4865
+ },
4866
+ close() {
4867
+ finish(void 0, /* @__PURE__ */ new Error("Voice question connection closed"));
4868
+ },
4869
+ get active() {
4870
+ return pending !== void 0;
4871
+ }
4872
+ };
4873
+ }
4874
+ //#endregion
4405
4875
  //#region src/remote-control-realtime.js
4406
4876
  const SIDEBAND_BASES = ["wss://api.openai.com/v1/live", "wss://realtime.chatgpt.com/v1/live"];
4407
4877
  const ACTIVATION_RETRY_MS = [
@@ -4477,7 +4947,12 @@ const outbound = {
4477
4947
  ...channel ? { channel } : {},
4478
4948
  content: content(text)
4479
4949
  }),
4480
- close: () => ({ type: "session.close" })
4950
+ close: () => ({ type: "session.close" }),
4951
+ interrupt: () => ({
4952
+ type: "session.context.append",
4953
+ channel: "developer",
4954
+ content: content("The user has started speaking. Stop your current speech immediately and listen. Do not finish or repeat the interrupted answer. Respond to the user when they finish speaking.")
4955
+ })
4481
4956
  };
4482
4957
  /** What the voice service sends, as the phone-facing notifications and the work to do. */
4483
4958
  function parseEvent(payload) {
@@ -4655,6 +5130,7 @@ function createRealtimeVoice(options) {
4655
5130
  clearTimeout(session.goodbye);
4656
5131
  clearTimeout(session.unhandledTimer);
4657
5132
  clearTimeout(session.closeTimer);
5133
+ session.questions?.close();
4658
5134
  flushTail(threadId, session);
4659
5135
  try {
4660
5136
  session.ws.send(JSON.stringify(outbound.close()));
@@ -4691,6 +5167,7 @@ function createRealtimeVoice(options) {
4691
5167
  tail: [],
4692
5168
  lines: [],
4693
5169
  working: 0,
5170
+ controls: /* @__PURE__ */ new Set(),
4694
5171
  flushTail: params.flushTranscriptTailOnSessionEnd !== false,
4695
5172
  silent: params.silentTailRecord === true,
4696
5173
  hangUp: params.hangUpOnGoodbye === true
@@ -4709,7 +5186,9 @@ function createRealtimeVoice(options) {
4709
5186
  for (const piece of appendChunks(text)) send(delegationId ? outbound.delegationAppend(delegationId, piece, channel) : outbound.sessionAppend(piece, channel));
4710
5187
  };
4711
5188
  session.speak = speak;
5189
+ session.questions = createVoiceQuestions({ speak: (text) => speak(void 0, text) });
4712
5190
  const runRequest = (input, delegationId) => {
5191
+ if (session.questions.consume(input, { delegation: true })) return;
4713
5192
  session.chain = session.chain.then(async () => {
4714
5193
  if (session.ended) return;
4715
5194
  try {
@@ -4745,6 +5224,14 @@ function createRealtimeVoice(options) {
4745
5224
  };
4746
5225
  const seenTypes = /* @__PURE__ */ new Set();
4747
5226
  ws.on("message", (data) => {
5227
+ try {
5228
+ const value = JSON.parse(String(data));
5229
+ const id = value.client_event_id ?? value.error?.event_id;
5230
+ if (id && session.controls.delete(id)) {
5231
+ if (value.type === "error") log.warn("voice", "the voice service refused an interruption command", String(value.error?.message ?? "").slice(0, 200));
5232
+ return;
5233
+ }
5234
+ } catch {}
4748
5235
  const event = parseEvent(String(data));
4749
5236
  if (!event) try {
4750
5237
  const type = JSON.parse(String(data))?.type;
@@ -4782,6 +5269,7 @@ function createRealtimeVoice(options) {
4782
5269
  at: Date.now()
4783
5270
  };
4784
5271
  else if (event.role === "user" && event.text.trim() !== "" && !(session.hangUp && isGoodbye(event.text))) {
5272
+ if (session.questions.consume(event.text.trim())) return;
4785
5273
  session.unhandled.push({
4786
5274
  text: event.text.trim(),
4787
5275
  at: Date.now()
@@ -4818,6 +5306,7 @@ function createRealtimeVoice(options) {
4818
5306
  if (session.ended || sessions.get(threadId) !== session) return;
4819
5307
  sessions.delete(threadId);
4820
5308
  session.ended = true;
5309
+ session.questions.close();
4821
5310
  flushTail(threadId, session);
4822
5311
  log.warn("voice", "the voice call closed");
4823
5312
  notify("thread/realtime/closed", {
@@ -4844,6 +5333,27 @@ function createRealtimeVoice(options) {
4844
5333
  return true;
4845
5334
  };
4846
5335
  return {
5336
+ askQuestion(threadId, request) {
5337
+ const session = sessions.get(threadId);
5338
+ return session ? session.questions.ask(request) : Promise.reject(/* @__PURE__ */ new Error("No voice call is active"));
5339
+ },
5340
+ interrupt(threadId) {
5341
+ const session = sessions.get(threadId);
5342
+ if (!session) return false;
5343
+ const event_id = crypto.randomUUID();
5344
+ if (session.controls.size > 20) session.controls.delete(session.controls.values().next().value);
5345
+ session.controls.add(event_id);
5346
+ try {
5347
+ session.ws.send(JSON.stringify({
5348
+ ...outbound.interrupt(),
5349
+ event_id
5350
+ }));
5351
+ return true;
5352
+ } catch {
5353
+ session.controls.delete(event_id);
5354
+ return false;
5355
+ }
5356
+ },
4847
5357
  start,
4848
5358
  stop,
4849
5359
  appendText: (threadId, text) => append(threadId, text, void 0),
@@ -5783,7 +6293,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
5783
6293
  const turn = emptyTurn();
5784
6294
  const userItem = {
5785
6295
  type: "userMessage",
5786
- id: randomUUID(),
6296
+ id: params.clientUserMessageId ?? randomUUID(),
5787
6297
  clientId: params.clientUserMessageId ?? null,
5788
6298
  content: [...text === "" ? [] : [{
5789
6299
  type: "text",
@@ -5803,6 +6313,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
5803
6313
  threadId: id,
5804
6314
  turn
5805
6315
  });
6316
+ turn.items.push(userItem);
5806
6317
  emit(id, "thread/status/changed", {
5807
6318
  threadId: id,
5808
6319
  status: {
@@ -6064,12 +6575,16 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6064
6575
  overriddenMetadata: null
6065
6576
  };
6066
6577
  },
6067
- "command/exec": async (params) => {
6578
+ "command/exec": async (params, { notify, signal }) => {
6068
6579
  const home = homeFolderAnswer(params?.command);
6069
6580
  if (home !== void 0) return home;
6070
6581
  const folders = await conversationFolders();
6071
6582
  try {
6072
- return await runGit(params, { folders });
6583
+ return phoneGitProbe(params?.command) ? await runPhoneGitProbe(params, {
6584
+ folders,
6585
+ notify,
6586
+ signal
6587
+ }) : await runGit(params, { folders });
6073
6588
  } catch (error) {
6074
6589
  trace({
6075
6590
  method: "command/exec:refused",
@@ -6596,6 +7111,11 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6596
7111
  };
6597
7112
  /** DSH's ask-user tool: show the questions on the phone that drives the turn, else leave them to DSH. */
6598
7113
  const onQuestion = (request, next) => {
7114
+ const threadId = request.agent?.session?.id;
7115
+ if (realtimeVoice?.active(threadId)) return realtimeVoice.askQuestion(threadId, request).catch((error) => {
7116
+ if (request.signal?.aborted) throw error;
7117
+ return next();
7118
+ });
6599
7119
  const found = phoneFor(request);
6600
7120
  trace({
6601
7121
  method: "hook:user-questions",
@@ -6897,6 +7417,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6897
7417
  return { answer };
6898
7418
  },
6899
7419
  stop: (sessionId) => realtimeVoice.stop(sessionId),
7420
+ interrupt: (sessionId) => realtimeVoice.interrupt(sessionId),
6900
7421
  end: (sessionId) => realtimeVoice.requestClose(sessionId),
6901
7422
  status: (sessionId) => realtimeVoice.status(sessionId)
6902
7423
  }),
@@ -11501,6 +12022,17 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
11501
12022
  if (error?.code === "unavailable") return publicError("unavailable", endpoint === "default-model/status" ? "The default model is unavailable" : "Could not save the default model");
11502
12023
  return publicError("internal", endpoint === "default-model/status" ? "Could not read the default model" : "Could not save the default model");
11503
12024
  }
12025
+ if (endpoint === "voice/interrupt") try {
12026
+ signal.throwIfAborted();
12027
+ if (typeof desktopVoice?.interrupt !== "function" || typeof payload?.sessionId !== "string") return publicError("unavailable", "Voice is unavailable");
12028
+ return {
12029
+ ok: true,
12030
+ value: { interrupted: desktopVoice.interrupt(payload.sessionId) }
12031
+ };
12032
+ } catch (error) {
12033
+ if (signal.aborted) throw error;
12034
+ return publicError("operation-error", "Could not interrupt voice");
12035
+ }
11504
12036
  if (endpoint === "voice/status") try {
11505
12037
  signal.throwIfAborted();
11506
12038
  if (!desktopVoice || typeof payload?.sessionId !== "string") return publicError("unavailable", "Voice is unavailable");
@@ -11543,9 +12075,9 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
11543
12075
  if (!voicePreview) return publicError("unavailable", "Voice preview is unavailable");
11544
12076
  if (endpoint === "voice/catalog") return {
11545
12077
  ok: true,
11546
- value: { voices: await voicePreview.available() }
12078
+ value: { voices: await voicePreview.available(payload?.language) }
11547
12079
  };
11548
- const value = await voicePreview.preview(payload?.voice);
12080
+ const value = await voicePreview.preview(payload?.voice, payload?.language);
11549
12081
  return value === void 0 ? publicError("not-found", "No sample for this voice") : {
11550
12082
  ok: true,
11551
12083
  value
@@ -11825,12 +12357,17 @@ const CATALOG_TTL_MS = 10 * 6e4;
11825
12357
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
11826
12358
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
11827
12359
  function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
11828
- let catalog;
12360
+ const catalogs = /* @__PURE__ */ new Map();
11829
12361
  const clips = /* @__PURE__ */ new Map();
11830
- const readCatalog = async () => {
12362
+ const languageOf = (value) => {
12363
+ const language = normalizeVoiceLanguage(value);
12364
+ return language === "auto" ? "en" : language;
12365
+ };
12366
+ const readCatalog = async (language) => {
12367
+ const catalog = catalogs.get(language);
11831
12368
  if (catalog && now() - catalog.at < CATALOG_TTL_MS) return catalog.voices;
11832
12369
  const { access, accountId } = await credentials();
11833
- const response = await fetch(`${base}/settings/voices`, {
12370
+ const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
11834
12371
  headers: {
11835
12372
  authorization: `Bearer ${access}`,
11836
12373
  "chatgpt-account-id": accountId,
@@ -11842,22 +12379,24 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
11842
12379
  if (!response.ok) throw new Error(`voice catalog HTTP ${response.status}`);
11843
12380
  const value = await response.json();
11844
12381
  const voices = (Array.isArray(value?.voices) ? value.voices : []).filter((entry) => typeof entry?.name === "string" && typeof entry?.preview_url === "string" && PREVIEW_HOSTS.test(entry.preview_url));
11845
- catalog = {
12382
+ catalogs.set(language, {
11846
12383
  at: now(),
11847
12384
  voices
11848
- };
12385
+ });
11849
12386
  return voices;
11850
12387
  };
11851
12388
  return {
11852
12389
  /** Which voices ChatGPT's own catalog offers right now (lower-case names), so the settings can mark the others unavailable. */
11853
- async available() {
11854
- return (await readCatalog()).map((entry) => entry.name.toLowerCase());
12390
+ async available(language) {
12391
+ return (await readCatalog(languageOf(language))).map((entry) => entry.name.toLowerCase());
11855
12392
  },
11856
12393
  /** The clip of one voice (by its Codex name, e.g. "spruce") as a data URL, with the catalog's description. */
11857
- async preview(voice) {
12394
+ async preview(voice, selectedLanguage) {
11858
12395
  if (typeof voice !== "string" || !/^[a-z]{2,16}$/u.test(voice)) return void 0;
11859
- if (clips.has(voice)) return clips.get(voice);
11860
- const entry = (await readCatalog()).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
12396
+ const language = languageOf(selectedLanguage);
12397
+ const key = `${language}:${voice}`;
12398
+ if (clips.has(key)) return clips.get(key);
12399
+ const entry = (await readCatalog(language)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
11861
12400
  if (!entry) return void 0;
11862
12401
  const response = await fetch(entry.preview_url, { signal: AbortSignal.timeout(15e3) });
11863
12402
  if (!response.ok) throw new Error(`voice sample HTTP ${response.status}`);
@@ -11870,7 +12409,7 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
11870
12409
  accent: typeof entry.accent === "string" ? entry.accent.slice(0, 60) : "",
11871
12410
  audio: `data:${type};base64,${bytes.toString("base64")}`
11872
12411
  };
11873
- if (clips.size < 40) clips.set(voice, result);
12412
+ if (clips.size < 40) clips.set(key, result);
11874
12413
  return result;
11875
12414
  }
11876
12415
  };
@@ -11939,6 +12478,7 @@ function withEndCallTool(desktopVoice, register) {
11939
12478
  return result;
11940
12479
  },
11941
12480
  end: (sessionId) => desktopVoice.end(sessionId),
12481
+ interrupt: (sessionId) => desktopVoice.interrupt(sessionId),
11942
12482
  status: (sessionId) => desktopVoice.status(sessionId)
11943
12483
  });
11944
12484
  }
@@ -11962,6 +12502,11 @@ const LEGACY_CREDENTIAL_REF = dshCredentials.credentialRef("WSL043_OPENAI_CODEX_
11962
12502
  const ACCOUNT_VAULT_KEY = dshCredentials.credentialKey("codex-subscription", "accounts");
11963
12503
  const WEB_ENTRY_ID = "web";
11964
12504
  const DSH_SEARCH_PROVIDER_FALLBACK = "deepseek-official";
12505
+ const SUBSCRIPTION_SEARCH_PROVIDER_IDS = /* @__PURE__ */ new Set([
12506
+ CODEX_SEARCH_PROVIDER_ID,
12507
+ CODEX_AUTO_SEARCH_PROVIDER_ID,
12508
+ DSH_ACCOUNT_SEARCH_PROVIDER_ID
12509
+ ]);
11965
12510
  const MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
11966
12511
  const REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
11967
12512
  const REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
@@ -11969,7 +12514,7 @@ function createSearchProviderSwitcher(loader) {
11969
12514
  const webEntry = () => [...loader.entries()].find((entry) => entry.options?.id === WEB_ENTRY_ID);
11970
12515
  const dshProviderId = () => {
11971
12516
  const configured = webEntry()?.options?.config?.searchProvider;
11972
- return typeof configured === "string" && configured.length > 0 ? configured : DSH_SEARCH_PROVIDER_FALLBACK;
12517
+ return typeof configured === "string" && configured.length > 0 && !SUBSCRIPTION_SEARCH_PROVIDER_IDS.has(configured) ? configured : DSH_SEARCH_PROVIDER_FALLBACK;
11973
12518
  };
11974
12519
  const current = () => {
11975
12520
  const value = webEntry()?.fiber?.config?.searchProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-codex-subscription",
3
- "version": "3.1.3",
3
+ "version": "3.1.4",
4
4
  "description": "Use ChatGPT and Codex subscriptions in DeepSeek Harness with OAuth, quota, safe resets, web search, images and Fast mode, and control DSH from the ChatGPT mobile app (Beta)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",