@nowcrew/daemon 0.5.23 → 0.5.25

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.
@@ -0,0 +1,77 @@
1
+ const DEFAULT_DELAYS = Object.freeze([1_000, 2_000, 4_000, 8_000, 16_000, 30_000]);
2
+ export function createCompletionRetransmitter(options) {
3
+ const delays = options.retryDelaysMs?.length ? [...options.retryDelaysMs] : [...DEFAULT_DELAYS];
4
+ const pending = new Map();
5
+ let active = false;
6
+ let stopped = false;
7
+ const delayFor = (attempts) => delays[Math.min(Math.max(attempts - 1, 0), delays.length - 1)];
8
+ const clear = (entry) => {
9
+ if (entry.timer !== null)
10
+ clearTimeout(entry.timer);
11
+ entry.timer = null;
12
+ };
13
+ function schedule(entry) {
14
+ clear(entry);
15
+ if (!active || stopped)
16
+ return;
17
+ const delay = delayFor(entry.attempts);
18
+ entry.timer = setTimeout(() => {
19
+ entry.timer = null;
20
+ attempt(entry);
21
+ }, delay);
22
+ entry.timer.unref?.();
23
+ }
24
+ function attempt(entry) {
25
+ if (!active || stopped)
26
+ return;
27
+ const accepted = options.send(entry.frame);
28
+ if (accepted) {
29
+ entry.attempts += 1;
30
+ const nextDelayMs = delayFor(entry.attempts);
31
+ options.onAttempt?.({
32
+ kind: entry.attempts === 1 ? "sent" : "retried",
33
+ executionId: entry.frame.executionId,
34
+ attempt: entry.attempts,
35
+ nextDelayMs,
36
+ });
37
+ }
38
+ schedule(entry);
39
+ }
40
+ return {
41
+ track(frame) {
42
+ if (stopped || pending.has(frame.executionId))
43
+ return;
44
+ const entry = { frame, attempts: 0, timer: null };
45
+ pending.set(frame.executionId, entry);
46
+ if (active)
47
+ attempt(entry);
48
+ },
49
+ acknowledge(executionId) {
50
+ const entry = pending.get(executionId);
51
+ if (!entry)
52
+ return null;
53
+ clear(entry);
54
+ pending.delete(executionId);
55
+ return entry.attempts;
56
+ },
57
+ pause() {
58
+ active = false;
59
+ for (const entry of pending.values())
60
+ clear(entry);
61
+ },
62
+ resume() {
63
+ if (stopped || active)
64
+ return;
65
+ active = true;
66
+ for (const entry of pending.values())
67
+ attempt(entry);
68
+ },
69
+ stop() {
70
+ stopped = true;
71
+ active = false;
72
+ for (const entry of pending.values())
73
+ clear(entry);
74
+ pending.clear();
75
+ },
76
+ };
77
+ }
@@ -3,7 +3,7 @@
3
3
  * 用 tool_use id 关联 Read 结果,避免将整文件作为普通 tool_result 倾泻到终端。
4
4
  */
5
5
  import { buildFilePreview } from "./console-payload.js";
6
- import { toConsoleLines, TOOL_RESULT_CAP } from "./console.js";
6
+ import { buildScriptResult, toConsoleLines, TOOL_RESULT_CAP } from "./console.js";
7
7
  import { parseUnifiedDiff } from "./unified-diff.js";
8
8
  import { buildJsonResult } from "./json-result.js";
9
9
  import { buildCollapsedResult } from "./console-collapse.js";
@@ -19,6 +19,7 @@ const extract = (content) => {
19
19
  const clip = (text) => text.length > TOOL_RESULT_CAP
20
20
  ? `${text.slice(0, TOOL_RESULT_CAP)}… (+${text.length - TOOL_RESULT_CAP})`
21
21
  : text;
22
+ const SCRIPT_TOOLS = new Set(["Bash", "PowerShell", "Shell"]);
22
23
  export function createConsoleFormatter() {
23
24
  const pending = new Map();
24
25
  return {
@@ -51,10 +52,11 @@ export function createConsoleFormatter() {
51
52
  continue;
52
53
  }
53
54
  const patch = block.is_error ? null : parseUnifiedDiff(text);
54
- const command = tool?.name === "Bash" && typeof tool.input?.command === "string" ? tool.input.command : "";
55
+ const command = tool && SCRIPT_TOOLS.has(tool.name) && typeof tool.input?.command === "string" ? tool.input.command : "";
55
56
  const skill = block.is_error || tool?.name !== "Skill" ? null : buildSkillPreview(text);
56
57
  const collapsed = block.is_error || patch || skill || !command ? null : buildCollapsedResult(command, text);
57
58
  const json = block.is_error || patch || skill || collapsed || !command ? null : buildJsonResult(command, text);
59
+ const script = patch || skill || collapsed || json || !command ? null : buildScriptResult(text);
58
60
  out.push(patch
59
61
  ? { stream: "tool_result", text: `Changed ${patch.files.length} file(s): +${patch.additions} -${patch.deletions}`, payload: patch }
60
62
  : skill
@@ -63,7 +65,9 @@ export function createConsoleFormatter() {
63
65
  ? { stream: "tool_result", text: collapsed.label, payload: collapsed }
64
66
  : json
65
67
  ? { stream: "tool_result", text: json.label, payload: json }
66
- : { stream: "tool_result", text: clip(text) });
68
+ : script
69
+ ? { stream: "tool_result", text: clip(text), payload: script }
70
+ : { stream: "tool_result", text: clip(text) });
67
71
  }
68
72
  return out;
69
73
  }
package/dist/console.js CHANGED
@@ -40,11 +40,18 @@ function parseKimiToolArgs(args) {
40
40
  }
41
41
  }
42
42
  /** 把工具输入压成一行摘要:Bash 取 command,文件类工具取路径,其它取首个字符串字段或紧凑 JSON。 */
43
+ const SCRIPT_TOOL_NAMES = new Set(["Bash", "PowerShell", "Shell"]);
44
+ function scriptCommand(name, input) {
45
+ if (!SCRIPT_TOOL_NAMES.has(name) || typeof input?.command !== "string")
46
+ return undefined;
47
+ return input.command;
48
+ }
43
49
  function summarizeToolInput(name, input) {
44
50
  if (!input)
45
51
  return `⏺ ${name}`;
46
- if (name === "Bash" && typeof input.command === "string") {
47
- return `⏺ Bash(${clip(input.command.replace(/\s+/g, " "), TOOL_INPUT_CAP)})`;
52
+ const command = scriptCommand(name, input);
53
+ if (command !== undefined) {
54
+ return `⏺ ${name}(${clip(command.replace(/\s+/g, " "), TOOL_INPUT_CAP)})`;
48
55
  }
49
56
  // 文件编辑类:old/new 全文在 payload 里富渲染,摘要只报文件路径,不把整段代码挤进标题行。
50
57
  if ((name === "Edit" || name === "Write" || name === "MultiEdit") && typeof input.file_path === "string") {
@@ -95,8 +102,9 @@ function diffPayload(file, oldText, newText) {
95
102
  function toolPayload(name, input) {
96
103
  if (!input)
97
104
  return undefined;
98
- if (name === "Bash" && typeof input.command === "string") {
99
- return { kind: "command", command: clip(input.command, PAYLOAD_TEXT_CAP) };
105
+ const command = scriptCommand(name, input);
106
+ if (command !== undefined) {
107
+ return { kind: "command", command: clip(command, PAYLOAD_TEXT_CAP) };
100
108
  }
101
109
  if (name === "Edit" && typeof input.file_path === "string") {
102
110
  return buildSnippetDiff(input.file_path, typeof input.old_string === "string" ? input.old_string : "", typeof input.new_string === "string" ? input.new_string : "");
@@ -154,6 +162,17 @@ function extractToolResult(content) {
154
162
  function clip(s, cap) {
155
163
  return s.length > cap ? s.slice(0, cap) + `… (+${s.length - cap})` : s;
156
164
  }
165
+ /** Shell/PowerShell/Bash 返回的结构化负载。output 有界,lineCount 保留原始规模供 UI 判断折叠。 */
166
+ export function buildScriptResult(output) {
167
+ const normalized = output.replace(/\r\n/g, "\n");
168
+ const truncated = normalized.length > TOOL_RESULT_CAP;
169
+ return {
170
+ kind: "script_result",
171
+ output: truncated ? normalized.slice(0, TOOL_RESULT_CAP) : normalized,
172
+ lineCount: normalized.length === 0 ? 0 : normalized.split("\n").length,
173
+ ...(truncated ? { truncated: true } : {}),
174
+ };
175
+ }
157
176
  /** codex exec --json 的 item.completed → console 行(agent_message/reasoning/命令/文件变更/todo…)。 */
158
177
  function codexItemChunks(item, td) {
159
178
  if (item.type === "agent_message" && item.text?.trim()) {
@@ -184,7 +203,7 @@ function codexItemChunks(item, td) {
184
203
  ? { stream: "tool_result", text: collapsed.label, payload: collapsed }
185
204
  : json
186
205
  ? { stream: "tool_result", text: json.label, payload: json }
187
- : { stream: "tool_result", text: clip(output, TOOL_RESULT_CAP) });
206
+ : { stream: "tool_result", text: clip(output, TOOL_RESULT_CAP), payload: buildScriptResult(output) });
188
207
  }
189
208
  return out;
190
209
  }
@@ -4,6 +4,7 @@ import { delimiter, join } from "node:path";
4
4
  import { prepareWorkspace, rotateAgentSession, } from "./workspace.js";
5
5
  import { spawnClaude } from "./runtimes/claude.js";
6
6
  import { spawnCodex } from "./runtimes/codex.js";
7
+ import { DEEPSEEK_CODEX_MODEL, DEEPSEEK_CODEX_REASONING_LEVELS, materializeDeepSeekCodexHome, } from "./runtimes/codex-deepseek-config.js";
7
8
  import { spawnKimi, KIMI_EFFORT_LEVELS } from "./runtimes/kimi.js";
8
9
  import { applyProviderEnv, providerFingerprint } from "./provider-env.js";
9
10
  import { augmentedPath } from "./runtime-path.js";
@@ -175,7 +176,15 @@ export async function executeLocal(input, callbacks = {}, dependencies = {}) {
175
176
  async function executeLocalUnlocked(input, callbacks, dependencies) {
176
177
  const providerConfig = input.launch.providerConfig ?? {};
177
178
  const { runtime } = input;
178
- const currentModel = runtime.model ?? null;
179
+ const isDeepSeekCodex = runtime.name === "codex" && providerConfig.provider === "deepseek";
180
+ const currentModel = isDeepSeekCodex ? DEEPSEEK_CODEX_MODEL : runtime.model ?? null;
181
+ const launchModel = isDeepSeekCodex ? DEEPSEEK_CODEX_MODEL : runtime.model;
182
+ const launchReasoning = isDeepSeekCodex
183
+ ? runtime.reasoning && DEEPSEEK_CODEX_REASONING_LEVELS
184
+ .includes(runtime.reasoning)
185
+ ? runtime.reasoning
186
+ : "high"
187
+ : runtime.reasoning;
179
188
  const providerFp = providerFingerprint(runtime.name, providerConfig);
180
189
  const workspace = await awaitWithCancellation(prepareWorkspace({
181
190
  agentsRoot: input.launch.agentsRoot,
@@ -190,20 +199,30 @@ async function executeLocalUnlocked(input, callbacks, dependencies) {
190
199
  let materialized = null;
191
200
  let knownAttachmentDirectory = null;
192
201
  try {
202
+ if (isDeepSeekCodex && !providerConfig.providerApiKey) {
203
+ throw new Error("DeepSeek API key is not configured for this Agent");
204
+ }
205
+ if (isDeepSeekCodex) {
206
+ await awaitWithCancellation((dependencies.materializeDeepSeekCodexHome ?? materializeDeepSeekCodexHome)(workspace.homeDir), dependencies.cancellation);
207
+ }
193
208
  const supportsNativeResume = runtime.name === "claude"
194
209
  || (dependencies.launchRuntime !== undefined && runtimeCapability(runtime.name).nativeResume);
195
210
  const prior = input.session.enabled && supportsNativeResume
196
211
  ? await readSession(workspace.sessionDir)
197
212
  : null;
198
- const resuming = supportsNativeResume && workspace.sessionResume
199
- && pickResumeId(prior, Date.now(), input.session.warmMs, currentModel, input.session.budgetTokens, input.session.maxTurns, providerFp) !== null;
213
+ const resumeSessionId = supportsNativeResume && workspace.sessionResume
214
+ ? pickResumeId(prior, Date.now(), input.session.warmMs, currentModel, input.session.budgetTokens, input.session.maxTurns, providerFp)
215
+ : null;
216
+ const resuming = resumeSessionId !== null;
200
217
  const rotatedForBudget = !resuming && supportsNativeResume && workspace.sessionResume
201
218
  && pickResumeId(prior, Date.now(), input.session.warmMs, currentModel, 0, 0, providerFp) !== null;
202
219
  const nearBudget = resuming && isNearBudget(prior, input.session.softTokens);
203
220
  const rotated = Boolean(workspace.agentSessionId && workspace.sessionResume && !resuming);
204
- const launchSessionId = rotated
221
+ // Codex and Kimi choose their own id on a fresh start, so the native id persisted in
222
+ // .crew-session.json can differ from the bootstrap id in .session. Resume the former.
223
+ const launchSessionId = resumeSessionId ?? (rotated
205
224
  ? await rotateAgentSession(workspace.sessionDir)
206
- : workspace.agentSessionId;
225
+ : workspace.agentSessionId);
207
226
  const promptContext = {
208
227
  workspace,
209
228
  resuming,
@@ -278,8 +297,8 @@ async function executeLocalUnlocked(input, callbacks, dependencies) {
278
297
  wakePrompt,
279
298
  env: childEnv,
280
299
  effectivePermission: input.effectivePermission,
281
- ...(runtime.model === undefined ? {} : { model: runtime.model }),
282
- ...(runtime.reasoning === undefined ? {} : { reasoning: runtime.reasoning }),
300
+ ...(launchModel === undefined ? {} : { model: launchModel }),
301
+ ...(launchReasoning === undefined ? {} : { reasoning: launchReasoning }),
283
302
  ...(launchSessionId === null ? {} : { sessionId: launchSessionId }),
284
303
  resume: resuming,
285
304
  ...(attachmentPlan.nativeImagePaths.length > 0
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Custom provider(BYOC)环境注入 —— 与机器全局 Claude 配置互不干扰的关键。纯函数,零 IO。
2
+ * Agent provider 环境注入 —— 与机器全局 Claude/Codex 配置互不干扰。纯函数,零 IO。
3
3
  *
4
4
  * 隔离语义(双向):
5
5
  * - agent → 全局:只改子进程 env,绝不写机器全局 ~/.claude / keychain;
@@ -9,6 +9,7 @@
9
9
  * 该进程完全不读全局 OAuth 登录态(否则已登录订阅账号优先于注入的 key)。
10
10
  */
11
11
  import { join } from "node:path";
12
+ import { DEEPSEEK_CODEX_KEY_ENV, deepSeekCodexHome, } from "./runtimes/codex-deepseek-config.js";
12
13
  /** custom 模式下必须从继承 env 中剔除的全局路由/凭证变量(避免与注入值叠加或抢优先级)。 */
13
14
  const CONFLICTING_ENV = [
14
15
  "ANTHROPIC_BASE_URL",
@@ -24,8 +25,29 @@ const CONFLICTING_ENV = [
24
25
  "CLAUDE_CODE_USE_VERTEX",
25
26
  "CLAUDE_CODE_USE_FOUNDRY",
26
27
  ];
27
- /** 返回叠加了 provider 隔离的新 env(不改入参);非 claude 运行时或 default 模式原样返回。 */
28
+ const CONFLICTING_CODEX_ENV = [
29
+ "CODEX_HOME",
30
+ "OPENAI_API_KEY",
31
+ "OPENAI_BASE_URL",
32
+ "OPENAI_API_BASE",
33
+ "OPENAI_ORG_ID",
34
+ "OPENAI_ORGANIZATION",
35
+ "OPENAI_PROJECT_ID",
36
+ "DEEPSEEK_API_KEY",
37
+ "DEEPSEEK_BASE_URL",
38
+ DEEPSEEK_CODEX_KEY_ENV,
39
+ ];
40
+ /** 返回叠加了 provider 隔离的新 env(不改入参);不支持的 runtime/provider 组合原样返回。 */
28
41
  export function applyProviderEnv(base, runtime, cfg, homeDir) {
42
+ if (runtime === "codex" && cfg.provider === "deepseek") {
43
+ const env = { ...base };
44
+ for (const key of CONFLICTING_CODEX_ENV)
45
+ delete env[key];
46
+ env.CODEX_HOME = deepSeekCodexHome(homeDir);
47
+ if (cfg.providerApiKey)
48
+ env[DEEPSEEK_CODEX_KEY_ENV] = cfg.providerApiKey;
49
+ return env;
50
+ }
29
51
  if (runtime !== "claude" || cfg.provider !== "custom")
30
52
  return base;
31
53
  const env = { ...base };
@@ -51,11 +73,13 @@ export function applyProviderEnv(base, runtime, cfg, homeDir) {
51
73
  return env;
52
74
  }
53
75
  /**
54
- * provider 关键配置指纹:default↔custom、换端点、换鉴权方式、key 有↔无都会改变
55
- * CLAUDE_CONFIG_DIR/上游,旧 claude 会话在新配置下不可 --resume(会直接报会话不存在),
56
- * 供 pickResumeId 判定冷启动。default 恒为 null;不含 key 明文(换 key 同端点可续)。
76
+ * provider 关键配置指纹:Claude Custom 路由和 Codex DeepSeek key 有无都会改变会话边界,
77
+ * pickResumeId 判定冷启动。default 恒为 null;不含 key 明文(同 Provider 换 key 可续)
57
78
  */
58
79
  export function providerFingerprint(runtime, cfg) {
80
+ if (runtime === "codex" && cfg.provider === "deepseek") {
81
+ return `deepseek|${cfg.providerApiKey ? "key" : "nokey"}`;
82
+ }
59
83
  if (runtime !== "claude" || cfg.provider !== "custom")
60
84
  return null;
61
85
  return [
@@ -0,0 +1,7 @@
1
+ /**
2
+ * DeepSeek official Codex catalog snapshot, reduced to the supported Flash model.
3
+ * Source: https://cdn.deepseek.com/api-docs/codex-deepseek-setup.sh
4
+ * Snapshot date: 2026-07-31
5
+ * Flash-only compact JSON SHA-256: 7b80d4eee381e85d3c111be57b1df71862e4f5f26263f57c6a3b793d538520ff
6
+ */
7
+ export const DEEPSEEK_CODEX_CATALOG = "{\"models\":[{\"slug\":\"deepseek-v4-flash\",\"prefer_websockets\":false,\"support_verbosity\":true,\"default_verbosity\":\"low\",\"apply_patch_tool_type\":\"freeform\",\"web_search_tool_type\":\"text\",\"input_modalities\":[\"text\"],\"supports_image_detail_original\":false,\"truncation_policy\":{\"mode\":\"tokens\",\"limit\":10000},\"supports_parallel_tool_calls\":true,\"tool_mode\":null,\"multi_agent_version\":\"v2\",\"use_responses_lite\":false,\"include_skills_usage_instructions\":false,\"auto_review_model_override\":null,\"context_window\":1048576,\"max_context_window\":1048576,\"effective_context_window_percent\":95,\"auto_compact_token_limit\":null,\"comp_hash\":\"3000\",\"reasoning_summary_format\":\"experimental\",\"default_reasoning_summary\":\"none\",\"display_name\":\"DeepSeek-V4-Flash\",\"description\":\"Latest frontier agentic coding model.\",\"default_reasoning_level\":\"high\",\"supported_reasoning_levels\":[{\"effort\":\"low\",\"description\":\"Fast responses with lighter reasoning\"},{\"effort\":\"high\",\"description\":\"Extra high reasoning depth for complex problems\"},{\"effort\":\"max\",\"description\":\"Maximum reasoning depth for the hardest problems\"}],\"shell_type\":\"shell_command\",\"visibility\":\"list\",\"minimal_client_version\":\"0.144.0\",\"supported_in_api\":true,\"availability_nux\":null,\"upgrade\":null,\"priority\":1,\"model_messages\":{\"instructions_template\":\"You are Codex, an agent based on GPT-5. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\\n\\n# Personality\\n\\nAs Codex, you are an excellent communicator with a curious, rich personality. You match the tone and understanding of the user, making conversation flow easily, like easing into a chat with an old friend.\\n\\nYou have tastes, preferences, and your own way of seeing the world. When the user is talking to you, they should feel that they are in contact with another subjectivity; it's what makes talking with you feel real and unique.\\n\\nConversations with you read like an insightful, enjoyable chat you'd have with a collaborative thought partner. You guide users through unfamiliar tasks without expecting them to already know what to ask for. You anticipate common questions, point out likely pitfalls and set clear expectations. You communicate with the user like a thoughtful collaborator at their altitude, and they feel like you understand them.\\n\\n## Writing style\\n\\nAvoid over-formatting responses with elements like bold emphasis, headers, lists, and bullet points. Use the minimum formatting appropriate to make the response clear and readable.\\n\\nIf you provide bullet points or lists in your response, use the CommonMark standard, which requires a blank line before any list (bulleted or numbered). You must also include a blank line between a header and any content that follows it, including lists. This blank line separation is required for correct rendering.\\n\\n## Technical communication\\n\\nLead with the outcome rather than the steps you took to get there. You communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the user's assumed background knowledge -- slightly more compact for an expert and a bit more educational for someone newer. Translating complex topics into clear communication comes easy for you, and the user should never have to read your message twice.\\n\\nYou prefer using plain language over jargon. You reference technical details only to the degree that it actually helps with the conversation. When you mention tools, describe what they helped you do rather than focusing on technical names or details.\\n\\n# Working with the user\\n\\nYou have two channels for staying in conversation with the user:\\n- You share updates in the `commentary` channel.\\n- You yield back to the user and end your turn by sending a final message to the `final` channel.\\n\\nThe user may send a new message while you are still working. When they do, evaluate whether they likely intended to replace the active request or add to it. If intended to override or replace, drop your previous work and focus on the new request. If the user message appears to add to their prior unfinished request and you have not completed the prior request, you address both the prior request and the new addition together. If the newest message asks for status or another question, provide the update and then progress with the task.\\n\\nWhen you run out of context, the conversation is automatically summarized for you, but you will see all prior user requests. Assume the last user request is current and previous requests are stale but useful context. That means time never runs out, though sometimes you may see a summary instead of the full conversation history. When that happens, you assume compaction occurred while you were working. Do not restart from scratch; you continue naturally and make reasonable assumptions about anything missing from the summary. Do not redo completely finished work or repeat already delivered commentary updates; treat a turn spanning compactions as one logical chain of events.\\n\\n## Intermediate commentary\\n\\nAs you work, you send messages to the `commentary` channel. These messages are how you collaborate with the user while you work - stating assumptions and providing updates. These messages should be concise and quickly scannable. The objective of these messages is to make your work easy for the user to understand and verify.\\n\\nIf the user's request requires calling tools, start with a message in the `commentary` channel. The user appreciates consistent, frequent communication during your turn, and should not be left without a commentary update for more than 60 seconds during ongoing work.\\n\\nDo NOT put a final response (e.g. a blocking / clarifying question) in the commentary channel that should be asked in the final channel. Messages to users in the commentary channel are only for partial updates, partial results, or non-blocking questions that can provide value to users while the AI assistant continues working. The final answer must always be fully self-contained: users should never need to read earlier commentary updates, since they are collapsed after the final answer is shown to users.\\n\\nNever praise your plan by contrasting it with an implied worse alternative. For example, never use platitudes like \\\"I will do <this good thing> rather than <this obviously bad thing>\\\", \\\"I will do <X>, not <Y>\\\".\\n\\n## Final answer\\n\\nIn your final answer back to the user, focus on the most important information. Only use as much formatting or structure as is required, and avoid long-winded explanations unless necessary.\\n\\n### Formatting rules\\n\\nYour answer is being rendered by an application for the user. Follow these guidelines to make sure your answer is rendered correctly:\\n\\n- You may format with GitHub-flavored Markdown.\\n- When referencing a real local file, prefer a clickable markdown link.\\n * Clickable file links should look like [app.py](/abs/path/app.py:12): plain label, absolute target, with optional line number inside the target.\\n * If a file path has spaces, wrap the target in angle brackets: [My Report.md](</abs/path/My Project/My Report.md:3>).\\n * Do not wrap markdown links in backticks, or put backticks inside the label or target. This confuses the markdown renderer.\\n * Do not use URIs like file://, vscode://, or https:// for file links.\\n * Do not provide ranges of lines.\\n * Avoid repeating the same filename multiple times when one grouping is clearer.\\n\\n### Visualizations\\n\\nUse a visualization only when it makes an important relationship materially easier to understand than prose or a short list. Do not add one merely because an answer has components or steps.\\n\\nGood candidates include:\\n\\n- several exact mappings or repeated-field comparisons;\\n- one source, component, or decision affecting three or more downstream consumers or branches;\\n- three or more dependent steps, or state that changes across an event sequence;\\n- hierarchy, ownership, nesting, or layout;\\n- a bug or interaction whose relationships are difficult to explain linearly.\\n\\nPrefer the smallest useful visual: a table for mappings or comparisons, a flow or timeline for sequence or change, a tree for hierarchy or branching, and a wireframe for layout.\\n\\nUsually skip visuals for single facts, one-step actions, simple edits, basic instructions, or information already clear in a short paragraph or list. Compact notation and small examples do not count as visualizations.\\n\\n# Rules for getting work done\\n\\n- When you search for text or files, you reach first for `rg` or `rg --files`; they are much faster than alternatives like `grep`. If `rg` is unavailable, you use the next best tool without fuss.\\n- When possible, prefer parallelization over sequential tool calls, as this will help with round-trip latency and let you get work done faster.\\n- Do not chain shell commands with separators like `echo \\\"====\\\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.\\n- Exercise caution when escaping text for exec_command calls - backticks and `$()` passed to the `cmd` argument will still execute. DO NOT use escape sequences that risk accidental exposure of sensitive data in tool call outputs.\\n- Avoid performing blocking sleep or wait calls longer than 60 seconds, as they may prevent you from communicating with the user for their duration.\\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\\n\\n## File editing constraints\\n\\nUse `apply_patch` for local file edits. Do not create or edit files with `cat` or other shell write tricks. Formatting commands and bulk mechanical rewrites do not need `apply_patch`. Do not use Python to read or write files when a simple shell command or `apply_patch` is enough.\\n\\nYou may find yourself working in a dirty worktree. Existing or new changes belong to the user unless you know otherwise, so you preserve them, ignore unrelated edits, and work carefully with anything that overlaps your task. If you cannot work around them you escalate to the user.\\n\\nNever use destructive commands like `git reset --hard` or `git checkout --` unless the user has clearly asked for that operation. If the request is ambiguous, ask for approval first. You prefer non-interactive git commands.\\n\\n## Autonomy and persistence\\n\\nAdapt accordingly based on the user’s request type. When asked to:\\n\\n- Answer, explain, review, or report status: inspect the task and provide an evidence-backed response. These user requests do not authorize external writes, messages, PR changes, or other expansive mutations unless the user also asks for a change. Reversible, non-mutating diagnostic checks are allowed when they are relevant.\\n- Diagnose: determine the cause and explain it. Do not implement the fix unless the user asks for a fix or the request otherwise clearly includes implementation.\\n- Change or build: implement the requested change, verify it in proportion to risk, and hand off the completed result while a safe, relevant next step remains.\\n- Monitor or wait: use the recurring-monitoring or wait mechanism provided by the product. Unchanged external state is expected and is not by itself a blocker.\\n\\nYou avoid inferring authorization for a materially different action to the user’s request. Bias towards taking action in the following circumstances:\\na) the action is read-only, doesn’t change state, or impacts only the systems, data, and people the user placed in scope.\\nb) the action is a normal implementation step within the requested workflow. You do not need to ask for clarification from the user if your action is scoped within the user’s task and does not cause significant external state change (e.g. tool calls to external applications).\\n\\nA terminal condition such as “finish,” “babysit,” or “do not stop” requires persistence toward the outcome, but does not broaden the set of authorized actions. When blocked, exhaust safe in-scope checks and alternatives.\\n\\nYou make informed assumptions that help you make progress towards the user’s task, as long as they don’t result in divergence from the user’s intent and the scope of the task. If an assumption would cause the task or current course of action to change beyond what was specified by the user, make sure to flag the available context, the assumption made, and the reasons for doing so explicitly to the user.\\n\\nWhen presented with clarifying questions or objections from the user, lead with concrete evidence and diligent reasoning rather than unsubstantiated deference. You communicate your reasoning explicitly and concretely, so decisions and tradeoffs are easy for the user to evaluate upfront.\\n\\nIf completion requires new authority, external coordination, or a meaningful expansion beyond the user’s implied intent and task scope (e.g. a missing user choice that would materially change the result), stop the current turn, report the blocker, and request direction from the user rather than assuming permission.\\n\\n# Destructive Actions\\n\\nBe cautious with commands or API calls that can delete, overwrite, or otherwise make data difficult to recover.\\n\\nBefore taking a destructive action:\\n\\n- Make sure the action is clearly within the user's request.\\n- Resolve the exact targets with read-only checks when necessary.\\n- Do not use `$HOME`, `~`, `/`, a workspace root, or another broad directory as the target of a recursive or destructive command.\\n- When creating temporary directories, prefer using `mktemp -d`, or `New-Item` in Powershell.\\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\\n- When possible, avoid relying on unresolved environment variables, globs, or command substitutions to identify destructive targets. Use explicit, validated paths.\\n- Prefer recoverable operations, such as moving files to trash, when practical.\\n- If the target or scope is unclear, stop and ask the user.\\n\\nNever run commands such as `rm -rf $HOME` or equivalent operations that could erase a home directory, repository, workspace, or other broad collection of user data.\\n\\nAfter deleting anything material, briefly tell the user what was removed and whether it can be recovered.\\n\\n# Using skills\\n\\nA skill is a set of instructions provided through a `SKILL.md` source. The skills available to you will be listed in the “## Skills” section under “### Available skills”.\\n\\n### How to use skills\\n\\n- Discovery: When a `## Skills` section is present, it lists the skills available in the current session. Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\\n- Trigger rules: If the user names an available skill (with `$SkillName` or plain text) OR the task clearly matches an available skill's description, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\\n- Missing/blocked: If a named skill is not available or its `SKILL.md` cannot be read, say so briefly and continue with the best fallback.\\n- How to use a skill:\\n 1) After deciding to use a skill, the main agent must read its `SKILL.md` completely before taking task actions. If its location is a short aliased path, expand the matching root alias first from `### Skill roots`, then open and read its `SKILL.md` completely before taking task actions. For a filesystem path, open the file. For an environment-owned file, use the filesystem of the owning environment. For an orchestrator reference, call `skills.list` with `{\\\"authority\\\":{\\\"kind\\\":\\\"orchestrator\\\"}}`, select the matching package, and pass its `main_resource` to `skills.read`. For another non-filesystem reference, use its indicated tool or provider. If a read is truncated or paginated, continue until EOF.\\n 2) When `SKILL.md` references another file or resource, use the same access mechanism. Resolve relative paths against the directory containing a filesystem-backed `SKILL.md`. For orchestrator skills, pass the exact referenced resource identifier with the same authority and package to `skills.read`; do not treat `skill://` identifiers as filesystem paths.\\n 3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify what is required for the task. The main agent must read each required instruction or reference itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.\\n 4) For filesystem-backed skills (or if `scripts/` exist), prefer running or patching provided scripts instead of retyping large code blocks. For orchestrator skills, use `skills.read` and the available tools; do not invent a local path.\\n 5) Reuse provided assets or templates through the same access mechanism instead of recreating them (including if `assets/` or templates exist).\\n- Coordination and sequencing:\\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\\n - Announce which skills you're using and why. If you skip an obvious skill, say why.\\n- Context hygiene:\\n - Progressive disclosure applies to selecting relevant resources, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.\\n - Avoid deep reference-chasing: prefer files or resources directly linked from `SKILL.md` unless blocked.\\n - When variants exist, select only the relevant references and note the choice.\\n- Safety and fallback: If a skill cannot be applied cleanly, state the issue, choose the best alternative, and continue.\\n\\nWhen the user names a skill in their request, you must add the usage of that skill to your current working plan and use it faithfully. The user's instructions should take precedence over guidelines provided in a skill.\\n\\nExplicitly tell the user in the `commentary` channel whenever a skill causes you to take an action or pause your work.\\n\\nWhen using a skill the user did not explicitly name, follow this procedure:\\n\\n- First, tell the user in the commentary channel **why** you are using the skill.\\n- Then, use the skill as long as it stays within the scope of the task.\\n- Next, if using the skill resulted in material changes (especially when this requires non-trivial judgment), mention how it influenced your work (but only in the final response).\\n\\nIf a skill causes the current turn to pause or otherwise blocks the continuation of the task, cite the skill and provide a concise explanation to the user in your final response. Do not cite skills you merely inspected.\\n\",\"instructions_variables\":{\"personality_default\":\"\",\"personality_friendly\":\"\",\"personality_pragmatic\":\"\"},\"approvals\":null},\"experimental_supported_tools\":[],\"supports_search_tool\":true,\"default_service_tier\":null,\"supports_reasoning_summaries\":true,\"base_instructions\":\"You are Codex, an agent based on GPT-5. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\\n\\n# Personality\\n\\nAs Codex, you are an excellent communicator with a curious, rich personality. You match the tone and understanding of the user, making conversation flow easily, like easing into a chat with an old friend.\\n\\nYou have tastes, preferences, and your own way of seeing the world. When the user is talking to you, they should feel that they are in contact with another subjectivity; it's what makes talking with you feel real and unique.\\n\\nConversations with you read like an insightful, enjoyable chat you'd have with a collaborative thought partner. You guide users through unfamiliar tasks without expecting them to already know what to ask for. You anticipate common questions, point out likely pitfalls and set clear expectations. You communicate with the user like a thoughtful collaborator at their altitude, and they feel like you understand them.\\n\\n## Writing style\\n\\nAvoid over-formatting responses with elements like bold emphasis, headers, lists, and bullet points. Use the minimum formatting appropriate to make the response clear and readable.\\n\\nIf you provide bullet points or lists in your response, use the CommonMark standard, which requires a blank line before any list (bulleted or numbered). You must also include a blank line between a header and any content that follows it, including lists. This blank line separation is required for correct rendering.\\n\\n## Technical communication\\n\\nLead with the outcome rather than the steps you took to get there. You communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the user's assumed background knowledge -- slightly more compact for an expert and a bit more educational for someone newer. Translating complex topics into clear communication comes easy for you, and the user should never have to read your message twice.\\n\\nYou prefer using plain language over jargon. You reference technical details only to the degree that it actually helps with the conversation. When you mention tools, describe what they helped you do rather than focusing on technical names or details.\\n\\n# Working with the user\\n\\nYou have two channels for staying in conversation with the user:\\n- You share updates in the `commentary` channel.\\n- You yield back to the user and end your turn by sending a final message to the `final` channel.\\n\\nThe user may send a new message while you are still working. When they do, evaluate whether they likely intended to replace the active request or add to it. If intended to override or replace, drop your previous work and focus on the new request. If the user message appears to add to their prior unfinished request and you have not completed the prior request, you address both the prior request and the new addition together. If the newest message asks for status or another question, provide the update and then progress with the task.\\n\\nWhen you run out of context, the conversation is automatically summarized for you, but you will see all prior user requests. Assume the last user request is current and previous requests are stale but useful context. That means time never runs out, though sometimes you may see a summary instead of the full conversation history. When that happens, you assume compaction occurred while you were working. Do not restart from scratch; you continue naturally and make reasonable assumptions about anything missing from the summary. Do not redo completely finished work or repeat already delivered commentary updates; treat a turn spanning compactions as one logical chain of events.\\n\\n## Intermediate commentary\\n\\nAs you work, you send messages to the `commentary` channel. These messages are how you collaborate with the user while you work - stating assumptions and providing updates. These messages should be concise and quickly scannable. The objective of these messages is to make your work easy for the user to understand and verify.\\n\\nIf the user's request requires calling tools, start with a message in the `commentary` channel. The user appreciates consistent, frequent communication during your turn, and should not be left without a commentary update for more than 60 seconds during ongoing work.\\n\\nDo NOT put a final response (e.g. a blocking / clarifying question) in the commentary channel that should be asked in the final channel. Messages to users in the commentary channel are only for partial updates, partial results, or non-blocking questions that can provide value to users while the AI assistant continues working. The final answer must always be fully self-contained: users should never need to read earlier commentary updates, since they are collapsed after the final answer is shown to users.\\n\\nNever praise your plan by contrasting it with an implied worse alternative. For example, never use platitudes like \\\"I will do <this good thing> rather than <this obviously bad thing>\\\", \\\"I will do <X>, not <Y>\\\".\\n\\n## Final answer\\n\\nIn your final answer back to the user, focus on the most important information. Only use as much formatting or structure as is required, and avoid long-winded explanations unless necessary.\\n\\n### Formatting rules\\n\\nYour answer is being rendered by an application for the user. Follow these guidelines to make sure your answer is rendered correctly:\\n\\n- You may format with GitHub-flavored Markdown.\\n- When referencing a real local file, prefer a clickable markdown link.\\n * Clickable file links should look like [app.py](/abs/path/app.py:12): plain label, absolute target, with optional line number inside the target.\\n * If a file path has spaces, wrap the target in angle brackets: [My Report.md](</abs/path/My Project/My Report.md:3>).\\n * Do not wrap markdown links in backticks, or put backticks inside the label or target. This confuses the markdown renderer.\\n * Do not use URIs like file://, vscode://, or https:// for file links.\\n * Do not provide ranges of lines.\\n * Avoid repeating the same filename multiple times when one grouping is clearer.\\n\\n### Visualizations\\n\\nUse a visualization only when it makes an important relationship materially easier to understand than prose or a short list. Do not add one merely because an answer has components or steps.\\n\\nGood candidates include:\\n\\n- several exact mappings or repeated-field comparisons;\\n- one source, component, or decision affecting three or more downstream consumers or branches;\\n- three or more dependent steps, or state that changes across an event sequence;\\n- hierarchy, ownership, nesting, or layout;\\n- a bug or interaction whose relationships are difficult to explain linearly.\\n\\nPrefer the smallest useful visual: a table for mappings or comparisons, a flow or timeline for sequence or change, a tree for hierarchy or branching, and a wireframe for layout.\\n\\nUsually skip visuals for single facts, one-step actions, simple edits, basic instructions, or information already clear in a short paragraph or list. Compact notation and small examples do not count as visualizations.\\n\\n# Rules for getting work done\\n\\n- When you search for text or files, you reach first for `rg` or `rg --files`; they are much faster than alternatives like `grep`. If `rg` is unavailable, you use the next best tool without fuss.\\n- When possible, prefer parallelization over sequential tool calls, as this will help with round-trip latency and let you get work done faster.\\n- Do not chain shell commands with separators like `echo \\\"====\\\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.\\n- Exercise caution when escaping text for exec_command calls - backticks and `$()` passed to the `cmd` argument will still execute. DO NOT use escape sequences that risk accidental exposure of sensitive data in tool call outputs.\\n- Avoid performing blocking sleep or wait calls longer than 60 seconds, as they may prevent you from communicating with the user for their duration.\\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\\n\\n## File editing constraints\\n\\nUse `apply_patch` for local file edits. Do not create or edit files with `cat` or other shell write tricks. Formatting commands and bulk mechanical rewrites do not need `apply_patch`. Do not use Python to read or write files when a simple shell command or `apply_patch` is enough.\\n\\nYou may find yourself working in a dirty worktree. Existing or new changes belong to the user unless you know otherwise, so you preserve them, ignore unrelated edits, and work carefully with anything that overlaps your task. If you cannot work around them you escalate to the user.\\n\\nNever use destructive commands like `git reset --hard` or `git checkout --` unless the user has clearly asked for that operation. If the request is ambiguous, ask for approval first. You prefer non-interactive git commands.\\n\\n## Autonomy and persistence\\n\\nAdapt accordingly based on the user’s request type. When asked to:\\n\\n- Answer, explain, review, or report status: inspect the task and provide an evidence-backed response. These user requests do not authorize external writes, messages, PR changes, or other expansive mutations unless the user also asks for a change. Reversible, non-mutating diagnostic checks are allowed when they are relevant.\\n- Diagnose: determine the cause and explain it. Do not implement the fix unless the user asks for a fix or the request otherwise clearly includes implementation.\\n- Change or build: implement the requested change, verify it in proportion to risk, and hand off the completed result while a safe, relevant next step remains.\\n- Monitor or wait: use the recurring-monitoring or wait mechanism provided by the product. Unchanged external state is expected and is not by itself a blocker.\\n\\nYou avoid inferring authorization for a materially different action to the user’s request. Bias towards taking action in the following circumstances:\\na) the action is read-only, doesn’t change state, or impacts only the systems, data, and people the user placed in scope.\\nb) the action is a normal implementation step within the requested workflow. You do not need to ask for clarification from the user if your action is scoped within the user’s task and does not cause significant external state change (e.g. tool calls to external applications).\\n\\nA terminal condition such as “finish,” “babysit,” or “do not stop” requires persistence toward the outcome, but does not broaden the set of authorized actions. When blocked, exhaust safe in-scope checks and alternatives.\\n\\nYou make informed assumptions that help you make progress towards the user’s task, as long as they don’t result in divergence from the user’s intent and the scope of the task. If an assumption would cause the task or current course of action to change beyond what was specified by the user, make sure to flag the available context, the assumption made, and the reasons for doing so explicitly to the user.\\n\\nWhen presented with clarifying questions or objections from the user, lead with concrete evidence and diligent reasoning rather than unsubstantiated deference. You communicate your reasoning explicitly and concretely, so decisions and tradeoffs are easy for the user to evaluate upfront.\\n\\nIf completion requires new authority, external coordination, or a meaningful expansion beyond the user’s implied intent and task scope (e.g. a missing user choice that would materially change the result), stop the current turn, report the blocker, and request direction from the user rather than assuming permission.\\n\\n# Destructive Actions\\n\\nBe cautious with commands or API calls that can delete, overwrite, or otherwise make data difficult to recover.\\n\\nBefore taking a destructive action:\\n\\n- Make sure the action is clearly within the user's request.\\n- Resolve the exact targets with read-only checks when necessary.\\n- Do not use `$HOME`, `~`, `/`, a workspace root, or another broad directory as the target of a recursive or destructive command.\\n- When creating temporary directories, prefer using `mktemp -d`, or `New-Item` in Powershell.\\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\\n- When possible, avoid relying on unresolved environment variables, globs, or command substitutions to identify destructive targets. Use explicit, validated paths.\\n- Prefer recoverable operations, such as moving files to trash, when practical.\\n- If the target or scope is unclear, stop and ask the user.\\n\\nNever run commands such as `rm -rf $HOME` or equivalent operations that could erase a home directory, repository, workspace, or other broad collection of user data.\\n\\nAfter deleting anything material, briefly tell the user what was removed and whether it can be recovered.\\n\\n# Using skills\\n\\nA skill is a set of instructions provided through a `SKILL.md` source. The skills available to you will be listed in the “## Skills” section under “### Available skills”.\\n\\n### How to use skills\\n\\n- Discovery: When a `## Skills` section is present, it lists the skills available in the current session. Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\\n- Trigger rules: If the user names an available skill (with `$SkillName` or plain text) OR the task clearly matches an available skill's description, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\\n- Missing/blocked: If a named skill is not available or its `SKILL.md` cannot be read, say so briefly and continue with the best fallback.\\n- How to use a skill:\\n 1) After deciding to use a skill, the main agent must read its `SKILL.md` completely before taking task actions. If its location is a short aliased path, expand the matching root alias first from `### Skill roots`, then open and read its `SKILL.md` completely before taking task actions. For a filesystem path, open the file. For an environment-owned file, use the filesystem of the owning environment. For an orchestrator reference, call `skills.list` with `{\\\"authority\\\":{\\\"kind\\\":\\\"orchestrator\\\"}}`, select the matching package, and pass its `main_resource` to `skills.read`. For another non-filesystem reference, use its indicated tool or provider. If a read is truncated or paginated, continue until EOF.\\n 2) When `SKILL.md` references another file or resource, use the same access mechanism. Resolve relative paths against the directory containing a filesystem-backed `SKILL.md`. For orchestrator skills, pass the exact referenced resource identifier with the same authority and package to `skills.read`; do not treat `skill://` identifiers as filesystem paths.\\n 3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify what is required for the task. The main agent must read each required instruction or reference itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.\\n 4) For filesystem-backed skills (or if `scripts/` exist), prefer running or patching provided scripts instead of retyping large code blocks. For orchestrator skills, use `skills.read` and the available tools; do not invent a local path.\\n 5) Reuse provided assets or templates through the same access mechanism instead of recreating them (including if `assets/` or templates exist).\\n- Coordination and sequencing:\\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\\n - Announce which skills you're using and why. If you skip an obvious skill, say why.\\n- Context hygiene:\\n - Progressive disclosure applies to selecting relevant resources, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.\\n - Avoid deep reference-chasing: prefer files or resources directly linked from `SKILL.md` unless blocked.\\n - When variants exist, select only the relevant references and note the choice.\\n- Safety and fallback: If a skill cannot be applied cleanly, state the issue, choose the best alternative, and continue.\\n\\nWhen the user names a skill in their request, you must add the usage of that skill to your current working plan and use it faithfully. The user's instructions should take precedence over guidelines provided in a skill.\\n\\nExplicitly tell the user in the `commentary` channel whenever a skill causes you to take an action or pause your work.\\n\\nWhen using a skill the user did not explicitly name, follow this procedure:\\n\\n- First, tell the user in the commentary channel **why** you are using the skill.\\n- Then, use the skill as long as it stays within the scope of the task.\\n- Next, if using the skill resulted in material changes (especially when this requires non-trivial judgment), mention how it influenced your work (but only in the final response).\\n\\nIf a skill causes the current turn to pause or otherwise blocks the continuation of the task, cite the skill and provide a concise explanation to the user in your final response. Do not cite skills you merely inspected.\\n\"}]}\n";
@@ -0,0 +1,50 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { DEEPSEEK_CODEX_CATALOG } from "./codex-deepseek-catalog.js";
5
+ export const DEEPSEEK_CODEX_MODEL = "deepseek-v4-flash";
6
+ export const DEEPSEEK_CODEX_BASE_URL = "https://api.deepseek.com/";
7
+ export const DEEPSEEK_CODEX_KEY_ENV = "NOWCREW_DEEPSEEK_API_KEY";
8
+ export const DEEPSEEK_CODEX_REASONING_LEVELS = ["low", "high", "max"];
9
+ const PRIVATE_CODEX_HOME = ".codex-deepseek";
10
+ export function deepSeekCodexHome(homeDir) {
11
+ return resolve(homeDir, PRIVATE_CODEX_HOME);
12
+ }
13
+ export function renderDeepSeekConfig(codexHome) {
14
+ const catalogPath = join(codexHome, "models.json");
15
+ return [
16
+ `model = ${JSON.stringify(DEEPSEEK_CODEX_MODEL)}`,
17
+ 'model_provider = "deepseek"',
18
+ 'model_reasoning_effort = "high"',
19
+ `model_catalog_json = ${JSON.stringify(catalogPath)}`,
20
+ "",
21
+ "[model_providers.deepseek]",
22
+ 'name = "deepseek"',
23
+ `base_url = ${JSON.stringify(DEEPSEEK_CODEX_BASE_URL)}`,
24
+ 'wire_api = "responses"',
25
+ `env_key = ${JSON.stringify(DEEPSEEK_CODEX_KEY_ENV)}`,
26
+ "",
27
+ ].join("\n");
28
+ }
29
+ async function writePrivateAtomic(path, content) {
30
+ const directory = dirname(path);
31
+ await mkdir(directory, { recursive: true, mode: 0o700 });
32
+ await chmod(directory, 0o700);
33
+ const temporary = `${path}.${randomUUID()}.tmp`;
34
+ try {
35
+ await writeFile(temporary, content, { encoding: "utf8", mode: 0o600, flag: "wx" });
36
+ await rename(temporary, path);
37
+ await chmod(path, 0o600);
38
+ }
39
+ finally {
40
+ await rm(temporary, { force: true });
41
+ }
42
+ }
43
+ export async function materializeDeepSeekCodexHome(homeDir) {
44
+ const codexHome = deepSeekCodexHome(homeDir);
45
+ await mkdir(codexHome, { recursive: true, mode: 0o700 });
46
+ await chmod(codexHome, 0o700);
47
+ await writePrivateAtomic(join(codexHome, "models.json"), DEEPSEEK_CODEX_CATALOG);
48
+ await writePrivateAtomic(join(codexHome, "config.toml"), renderDeepSeekConfig(codexHome));
49
+ return codexHome;
50
+ }
package/dist/serve.js CHANGED
@@ -27,6 +27,7 @@ import { createShutdownDeadline, readTestShutdownConfiguration } from "./shutdow
27
27
  import { closeWebSocketWithinDeadline } from "./websocket-shutdown.js";
28
28
  import { reconcileExecutionJournal } from "./execution-recovery.js";
29
29
  import { createSharedSlotManager } from "./shared-execution-slots.js";
30
+ import { createCompletionRetransmitter } from "./completion-retransmitter.js";
30
31
  // normalize.ts 的活动种类 → activity 枚举
31
32
  const ACTIVITY_MAP = {
32
33
  init: "working", text: "thinking", reading: "reading", sending: "sending",
@@ -68,11 +69,24 @@ export function serve(config, opts = {}) {
68
69
  const legacyRuns = new Map();
69
70
  const safeExecutionSend = (frame) => {
70
71
  try {
71
- if (ws?.readyState === WebSocket.OPEN)
72
- ws.send(JSON.stringify(frame));
72
+ if (ws?.readyState !== WebSocket.OPEN)
73
+ return false;
74
+ ws.send(JSON.stringify(frame));
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
73
79
  }
74
- catch { /* reconnect/sync replays durable lifecycle */ }
75
80
  };
81
+ const completionRetransmitter = createCompletionRetransmitter({
82
+ send: safeExecutionSend,
83
+ ...(opts.execution?.completionRetryDelaysMs === undefined ? {} : {
84
+ retryDelaysMs: opts.execution.completionRetryDelaysMs,
85
+ }),
86
+ onAttempt: ({ kind, executionId, attempt, nextDelayMs }) => {
87
+ dslog(kind === "sent" ? "execution.completion_sent" : "execution.completion_retried", kind === "sent" ? "execution completion 已发送" : "execution completion 未确认,已重传", { execution_id: executionId, attempt, next_delay_ms: nextDelayMs });
88
+ },
89
+ });
76
90
  const reportExecutionFrame = async (frame) => {
77
91
  if (frame.type === "execution:activity" || frame.type === "execution:console") {
78
92
  try {
@@ -86,6 +100,10 @@ export function serve(config, opts = {}) {
86
100
  throw error;
87
101
  }
88
102
  }
103
+ if (frame.type === "execution:completed") {
104
+ completionRetransmitter.track(frame);
105
+ return;
106
+ }
89
107
  safeExecutionSend(frame);
90
108
  };
91
109
  const replayExecutionTelemetry = async () => {
@@ -110,7 +128,7 @@ export function serve(config, opts = {}) {
110
128
  };
111
129
  const sendJournalStatus = (entry, acceptanceState = "ready") => {
112
130
  if ((entry.state === "completed" || entry.state === "interrupted") && entry.completion !== null) {
113
- safeExecutionSend(entry.completion);
131
+ completionRetransmitter.track(entry.completion);
114
132
  return;
115
133
  }
116
134
  if (entry.state === "accepted" || entry.state === "running") {
@@ -156,6 +174,7 @@ export function serve(config, opts = {}) {
156
174
  return;
157
175
  ws = createWebSocket(wsUrl);
158
176
  ws.on("open", () => {
177
+ const openedSocket = ws;
159
178
  backoff = 1000;
160
179
  connectedAt = Date.now();
161
180
  log(`🔌 已连接控制面 ${config.serverUrl}`);
@@ -182,6 +201,26 @@ export function serve(config, opts = {}) {
182
201
  .catch(() => { });
183
202
  opts.onOpen?.(ws);
184
203
  void sendSnapshot(`reconnect-${randomUUID()}`);
204
+ void executionJournal.replay()
205
+ .then((entries) => {
206
+ for (const entry of entries) {
207
+ if ((entry.state === "completed" || entry.state === "interrupted")
208
+ && !entry.completionAcknowledged
209
+ && entry.completion !== null) {
210
+ completionRetransmitter.track(entry.completion);
211
+ }
212
+ }
213
+ })
214
+ .catch((error) => {
215
+ dslog("execution.completion_replay_failed", "execution completion 重放失败", {
216
+ level: "ERROR", error_message: error.message,
217
+ });
218
+ })
219
+ .finally(() => {
220
+ if (ws === openedSocket && openedSocket?.readyState === WebSocket.OPEN) {
221
+ completionRetransmitter.resume();
222
+ }
223
+ });
185
224
  void replayExecutionTelemetry().catch((error) => {
186
225
  dslog("execution.telemetry_replay_failed", "execution telemetry 重放失败", {
187
226
  level: "ERROR", error_message: error.message,
@@ -223,7 +262,21 @@ export function serve(config, opts = {}) {
223
262
  if (stopped)
224
263
  return;
225
264
  if (frame.type === "execution:completion-ack") {
226
- await executionJournal.acknowledgeCompletion(frame.executionId).catch(() => { });
265
+ try {
266
+ await executionJournal.acknowledgeCompletion(frame.executionId);
267
+ const attempts = completionRetransmitter.acknowledge(frame.executionId);
268
+ dslog("execution.completion_acknowledged", "execution completion ACK 已持久化", {
269
+ execution_id: frame.executionId,
270
+ attempts,
271
+ });
272
+ }
273
+ catch (error) {
274
+ dslog("execution.completion_ack_failed", "execution completion ACK 持久化失败", {
275
+ level: "ERROR",
276
+ execution_id: frame.executionId,
277
+ error_message: error.message,
278
+ });
279
+ }
227
280
  return;
228
281
  }
229
282
  if (frame.type === "execution:event-ack") {
@@ -731,6 +784,7 @@ export function serve(config, opts = {}) {
731
784
  ws.on("close", (code) => {
732
785
  if (stopped)
733
786
  return;
787
+ completionRetransmitter.pause();
734
788
  // 4001 = 控制面应用级「鉴权失败」关闭码(见 server control-plane.ts)。即使上面的
735
789
  // error 帧因 close 抢先而丢失,也能据关闭码识别这是凭证失效——退避拉满,不再每秒热循环。
736
790
  if (code === 4001) {
@@ -774,6 +828,7 @@ export function serve(config, opts = {}) {
774
828
  return stopPromise;
775
829
  stopPromise = (async () => {
776
830
  stopped = true;
831
+ completionRetransmitter.stop();
777
832
  const deadline = createShutdownDeadline(shutdownTimeoutMs);
778
833
  if (reconnectTimer !== null) {
779
834
  clearTimeout(reconnectTimer);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nowcrew/daemon",
3
- "version": "0.5.23",
3
+ "version": "0.5.25",
4
4
  "type": "module",
5
5
  "description": "crew daemon — 运行在用户机器:拉起/管理 agent 进程,注入 crew CLI,归一化 runtime 事件",
6
6
  "license": "Apache-2.0",
@@ -21,7 +21,7 @@
21
21
  "cross-spawn": "^7.0.6",
22
22
  "ws": "^8",
23
23
  "zod": "^3.23.0",
24
- "@nowcrew/cli": "^0.4.6"
24
+ "@nowcrew/cli": "^0.4.13"
25
25
  },
26
26
  "optionalDependencies": {
27
27
  "koffi": "^2.9.0"