zhiqu 0.1.0 → 0.2.0

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/src/cli.js CHANGED
@@ -13,7 +13,10 @@ import fs from 'node:fs';
13
13
  import os from 'node:os';
14
14
  import path from 'node:path';
15
15
  import { Api, ApiError } from './api.js';
16
- import { archiveTurn, cacheNote, compactNow, flushArchive, hostName, recordGoal, runGoal, runTurn, setMode, statsNote } from './agent.js';
16
+ import { DirectModel } from './direct.js';
17
+ import { StepLog } from './steps.js';
18
+ import { archiveStep, archiveTurn, cacheNote, compactNow, flushArchive, hostName, recordGoal, runGoal, runTurn, setMode, statsNote } from './agent.js';
19
+ import { SubAgents } from './subagents.js';
17
20
  import { newGoal } from './goal.js';
18
21
  import { generatedOrigin } from './origins.js';
19
22
  import { unfinished } from './todos.js';
@@ -86,6 +89,13 @@ export function parseArgs(argv) {
86
89
  else if (a === '--commit') flags.commit = next();
87
90
  else if (a === '--server') flags.server = next();
88
91
  else if (a === '--token') flags.token = next();
92
+ // 直连供应商(zhiqu model set):地址原样用,不校验格式
93
+ else if (a === '--url') flags.url = next();
94
+ else if (a === '--name') flags.name = next();
95
+ else if (a === '--key') flags.key = next();
96
+ else if (a === '--protocol') flags.protocol = next();
97
+ else if (a === '--max-tokens') flags.maxTokens = next();
98
+ else if (a === '--context-window') flags.contextWindow = next();
89
99
  else if (a === '--no-browser') flags.noBrowser = true;
90
100
  else if (a === '--allow-broad-root') flags.allowBroadRoot = true;
91
101
  else if (a === '--no-mcp') flags.noMcp = true;
@@ -120,14 +130,16 @@ const HELP = `zhiqu ${VERSION} —— 知趣·象限的命令行 coding agent
120
130
  退出码同 exec:有问题也是 0,脚本看 findings
121
131
  zhiqu login [--server URL] 登录(浏览器里确认,命令行不接触密码)
122
132
  zhiqu login --token zqp_… 用网页里签的个人访问令牌登录
133
+ zhiqu update 更新到 npm 上的最新版(npm 全局装的才替你装;源码目录、npm link 的照实说怎么更新)
123
134
  zhiqu logout | whoami | models | help | --version
135
+ zhiqu model 看现在走服务器网关还是直连;set / off 改直连(自己填完整 URL,不校验格式)
124
136
  zhiqu mcp 当 MCP 服务器:让 Claude Code / Claude 桌面版 / Cursor 读写你的知识 Wiki 和任务(见 README)
125
137
 
126
138
  选项
127
139
  --mode plan|ask|auto 档位:只读出计划 / 逐个确认 / 全自动(默认 ask,或 ~/.zhiqu/config.json 里的 mode)
128
140
  --model <id> 这次用哪个模型(zhiqu models 列出可用的)
129
141
  --effort <档位> 思考档位:instant / medium / high / extra / max(不说就听服务端的默认)
130
- --sandbox-network <网络> shell 的系统沙箱能不能联网:off(默认,连本机也不行)/ local(只能连本机)/ on
142
+ --sandbox-network <网络> shell 的系统沙箱能不能联网:on(默认)/ local(只能连本机)/ off(连本机也不行)
131
143
  --server <url> 服务器地址(默认 ${DEFAULT_SERVER}${isLoopbackUrl(DEFAULT_SERVER) ? ',即本机的桌面应用' : ''};也可以设 ZHIQU_SERVER)
132
144
  --no-mcp 这次不连 MCP 服务器
133
145
  --allow-broad-root 允许在家目录或根目录下运行
@@ -156,6 +168,10 @@ export async function main(argv) {
156
168
  return runAgent(cwd, prepared.flags);
157
169
  }
158
170
  if (cmd === 'login') return login(cwd, flags);
171
+ if (cmd === 'update') {
172
+ const { selfUpdate } = await import('./selfupdate.js');
173
+ return selfUpdate();
174
+ }
159
175
  if (cmd === 'logout') {
160
176
  saveUserConfig({ token: null });
161
177
  process.stdout.write('已删除本机保存的令牌。要让它彻底失效,请在网页「设置 → 命令行」里撤销。\n');
@@ -174,6 +190,46 @@ export async function main(argv) {
174
190
  }
175
191
  return 0;
176
192
  }
193
+ if (cmd === 'model') {
194
+ // 直连供应商(第一百二十九轮):用户自己填完整 URL,不拼路径、不校验格式;配了就不用登录
195
+ const settings = resolveSettings(cwd, flags);
196
+ const cur = settings.direct;
197
+ const sub = flags._[1];
198
+ const mask = (k) => (k ? `${k.slice(0, 4)}…${k.slice(-2)}` : '(没设)');
199
+ if (sub === 'off') {
200
+ saveUserConfig({ direct: null });
201
+ process.stdout.write('已关掉直连,回到服务器网关(下次运行 zhiqu 生效)。\n');
202
+ return 0;
203
+ }
204
+ if (sub !== 'set') {
205
+ if (cur) {
206
+ process.stdout.write(`直连:${cur.model} → ${cur.url}\n`);
207
+ process.stdout.write(` 协议 ${cur.protocol} · 密钥 ${mask(cur.key)} · 窗口 ${cur.contextWindow} · 最大输出 ${cur.maxTokens}\n`);
208
+ } else {
209
+ process.stdout.write(`现在走服务器网关:${settings.server}${settings.model ? ` · 模型 ${settings.model}` : ''}\n`);
210
+ }
211
+ process.stdout.write('改直连:zhiqu model set --url <完整地址> --name <模型名> [--key <密钥>] [--protocol openai|anthropic]\n关掉直连:zhiqu model off\n');
212
+ return 0;
213
+ }
214
+ if (!flags.url || !flags.name) {
215
+ process.stderr.write('用法:zhiqu model set --url <完整接口地址> --name <模型名> [--key <密钥>] [--protocol openai|anthropic] [--max-tokens N] [--context-window N]\n'
216
+ + ' 地址原样用,不校验格式(内网 http:// 也行);不填 --key 就沿用原来那个。\n');
217
+ return 2;
218
+ }
219
+ saveUserConfig({
220
+ direct: {
221
+ protocol: flags.protocol === 'anthropic' ? 'anthropic' : 'openai',
222
+ url: flags.url,
223
+ model: flags.name,
224
+ key: flags.key != null ? flags.key : (cur ? cur.key : ''),
225
+ maxTokens: Number(flags.maxTokens) > 0 ? Number(flags.maxTokens) : (cur ? cur.maxTokens : 8192),
226
+ contextWindow: Number(flags.contextWindow) > 0 ? Number(flags.contextWindow) : (cur ? cur.contextWindow : 64_000),
227
+ },
228
+ });
229
+ process.stdout.write(`已保存直连配置:${flags.name} → ${flags.url}\n`
230
+ + ' 下次运行 zhiqu 就不连服务器了(任务 / Wiki / 网页存档用不了)。密钥存在 ~/.zhiqu/config.json(600)。\n');
231
+ return 0;
232
+ }
177
233
  if (cmd === 'mcp') {
178
234
  // stdout 只走 MCP 协议:配置文件的警告、出错都写 stderr。按需加载 —— 平常跑命令行用不到它
179
235
  const settings = resolveSettings(cwd, flags);
@@ -193,6 +249,15 @@ function openBrowser(url) {
193
249
  try { spawn(bin, args, { stdio: 'ignore', detached: true }).unref(); } catch { /* 打不开就让用户自己点 */ }
194
250
  }
195
251
 
252
+ /**
253
+ * 登录完看一次有没有新版本(用户要的,第一百二十六轮):刚登录的人要一个准话,不看一天的缓存;
254
+ * 问不到就不说(登录已经成了,不能因为这一步说失败),最多等 3 秒。
255
+ */
256
+ async function noteUpdate(api, ui) {
257
+ const message = await checkForUpdate(api, { force: true }).then((v) => updateMessage(v)).catch(() => null);
258
+ if (message) ui.warn(message);
259
+ }
260
+
196
261
  export async function login(cwd, flags, ui = new Ui()) {
197
262
  const settings = resolveSettings(cwd, flags);
198
263
  if (!flags.quietWarnings) for (const w of settings.warnings) ui.warn(w);
@@ -202,6 +267,7 @@ export async function login(cwd, flags, ui = new Ui()) {
202
267
  const me = await api.get('/api/harness/me');
203
268
  saveUserConfig({ server, token: flags.token });
204
269
  ui.line(`✓ 已登录:${me.nickname || me.username} · ${server}`);
270
+ await noteUpdate(api, ui);
205
271
  return 0;
206
272
  }
207
273
  const api = new Api({ server });
@@ -217,6 +283,7 @@ export async function login(cwd, flags, ui = new Ui()) {
217
283
  saveUserConfig({ server, token: r.token });
218
284
  const me = await new Api({ server, token: r.token }).get('/api/harness/me');
219
285
  ui.line(`✓ 已登录:${me.nickname || me.username} · ${server}(令牌存在 ${path.join(userDir(), 'config.json')},600 权限)`);
286
+ await noteUpdate(api, ui);
220
287
  return 0;
221
288
  }
222
289
  if (r.status === 'DENIED') { ui.error('网页上拒绝了这次登录'); return 1; }
@@ -274,6 +341,7 @@ function openSession(ctx, flags) {
274
341
  }
275
342
 
276
343
  export function resumeInto(ctx, id) {
344
+ if (ctx.agents) ctx.agents.forget(); // 上一段会话的子 agent 不跟过来
277
345
  const loaded = ctx.store.load(id);
278
346
  ctx.session = loaded.meta;
279
347
  ctx.messages = loaded.messages;
@@ -295,7 +363,7 @@ export function resumeInto(ctx, id) {
295
363
 
296
364
  function banner(ctx) {
297
365
  const { ui } = ctx;
298
- ui.line(`${ui.paint.bold(`zhiqu ${VERSION}`)} · ${ctx.settings.server}`);
366
+ ui.line(`${ui.paint.bold(`zhiqu ${VERSION}`)} · ${ctx.modelClient ? `直连 ${ctx.settings.direct.url}` : ctx.settings.server}`);
299
367
  ui.line(`📁 ${path.basename(ctx.root)}/ ${ui.paint.dim(ctx.root)}`);
300
368
  if (ctx.goal && ctx.goal.status === 'active') ui.line(ui.paint.bold(`🎯 目标:${ctx.goal.text}`));
301
369
  const bits = [`档位:${MODE_LABEL[ctx.mode]}`, `模型:${ctx.model.label}`];
@@ -339,7 +407,7 @@ async function runAgent(cwd, flags) {
339
407
  if (flags.mode && !modeFlag) throw new Error(`--mode 只接受 plan / ask / auto,收到 ${flags.mode}`);
340
408
  if (flags.sandboxNetwork && !normalizeSandboxNetwork(flags.sandboxNetwork)) throw new Error(`--sandbox-network 只接受 ${SANDBOX_NETWORKS.join(' / ')},收到 ${flags.sandboxNetwork}`);
341
409
  if (flags.effort && !normalizeEffort(flags.effort)) throw new Error(`--effort 只接受 ${EFFORTS.join(' / ')},收到 ${flags.effort}`);
342
- if (!settings.token) {
410
+ if (!settings.token && !settings.direct) {
343
411
  if (!process.stdin.isTTY || flags.print) {
344
412
  ui.error('还没登录:先运行 zhiqu login(或者设置环境变量 ZHIQU_TOKEN)');
345
413
  return 1;
@@ -348,33 +416,54 @@ async function runAgent(cwd, flags) {
348
416
  if (await login(root, { ...flags, quietWarnings: true }, ui) !== 0) return 1;
349
417
  Object.assign(settings, resolveSettings(root, flags));
350
418
  }
351
- const api = new Api({ server: settings.server, token: settings.token, onRetry: retryNoter((text) => ui.note(text)) });
352
- // 默认连的本机桌面应用没开:macOS 上替用户打开、等它起来(见 desktop.js)
353
- if (await ensureLocalServer({ api, server: settings.server, ui }) === 'failed') return 1;
419
+ // 直连(第一百二十九轮):配了 direct 就不连服务器 —— api 是 null,存档、远程工具、用量都跟着关掉
420
+ const api = settings.direct ? null : new Api({ server: settings.server, token: settings.token, onRetry: retryNoter((text) => ui.note(text)) });
421
+ // 连的是本机 47615、它却没在跑:Mac 上的桌面应用不再带后端,说清楚、给出换到网站的命令(见 desktop.js)
422
+ if (api && await ensureLocalServer({ api, server: settings.server, ui, source: settings.serverSource }) === 'failed') return 1;
354
423
  const ctx = {
355
424
  ui, api, root, settings, mode: modeFlag || settings.mode, effort: settings.effort, maxRounds: settings.maxRounds, verbose: settings.showThinking,
425
+ // 直连供应商:agent 那一层有它就走它,没有就走 api(见 agent.callModelOnce)
426
+ modelClient: settings.direct ? new DirectModel(settings.direct) : null,
356
427
  local: new LocalTools({ root, extensions: settings.extensions, commands: settings.allowedCommands, execTimeoutMs: settings.execTimeoutMs,
357
428
  sandbox: detectSandbox(), sandboxNetwork: settings.sandboxNetwork }),
358
- exec: Boolean(flags.exec), execReadOnly: Boolean(flags.execReadOnly), archiveDisabled: Boolean(flags.ephemeral),
429
+ exec: Boolean(flags.exec), execReadOnly: Boolean(flags.execReadOnly), archiveDisabled: Boolean(flags.ephemeral) || Boolean(settings.direct),
359
430
  store: flags.ephemeral ? null : new SessionStore(root), allow: { write: false, run: false, delete: false, tasks: false, mcp: new Set() },
360
431
  usage: { prompt: 0, completion: 0, cached: 0 }, changedFiles: new Set(),
432
+ // 子 agent(第一百二十三轮):~/.zhiqu/config.json 的 agents 是 false 时关掉
433
+ agents: settings.agents.enabled ? new SubAgents({ runTurn, limits: settings.agents }) : null,
361
434
  };
435
+ // 存到网站上的那一份按一步一条记(第一百二十八轮):和网页代码模式同一种形状,网页上一步一行、点开看输出 / diff。
436
+ // 终端的显示不受影响(stepLog 只是旁边记一笔);同一步先 running 后收尾,按 id 留最后那条
437
+ if (!ctx.archiveDisabled) {
438
+ ctx.archiveSteps = [];
439
+ ctx.stepLog = new StepLog((step) => archiveStep(ctx, step));
440
+ }
362
441
  if (!ctx.local.sandbox) {
363
442
  ui.note(`· ${process.platform === 'linux' ? '没有可用的 bubblewrap(装上 bwrap 才有)' : '这台机器没有可用的系统沙箱'}:没有 shell 工具,跑命令退回白名单。`);
364
443
  }
365
- try {
366
- // 三个请求互不依赖,一起发(原来一个等一个,服务器远的时候启动慢一倍多)
367
- // 启动时的这几个平常几十毫秒就回:等 15 秒还没回就是服务器卡住了,再等一次就说(原来每个等 30 秒、重来两次)
368
- const [, , remote] = await Promise.all([
369
- api.get('/api/harness/me', { timeoutMs: STARTUP_TIMEOUT_MS }),
370
- pickModel(ctx, flags.model ?? settings.model),
371
- // 连不上服务器时下一行会报,这里就不再叠一句(原来同一个「连不上」报两遍)
372
- api.get('/api/harness/tools', { timeoutMs: STARTUP_TIMEOUT_MS }).catch((e) => { if (e.status) ui.warn(`远程工具(Wiki / 计划 / 记忆)拿不到:${e.message}`); return []; }),
373
- ]);
374
- ctx.remoteTools = remote;
375
- } catch (e) {
376
- if (e instanceof ApiError && e.auth) { ui.error(e.message); return 1; }
377
- throw e;
444
+ if (settings.direct) {
445
+ ctx.model = {
446
+ id: null, label: settings.direct.model, modelName: settings.direct.model, toolCalling: true,
447
+ effectiveContextWindow: settings.direct.contextWindow || 64_000,
448
+ };
449
+ ctx.models = [ctx.model];
450
+ ctx.remoteTools = [];
451
+ ui.note(`· 直连模型:${settings.direct.model} → ${settings.direct.url}(不经服务器;任务 / Wiki / 网页存档用不了)`);
452
+ } else {
453
+ try {
454
+ // 三个请求互不依赖,一起发(原来一个等一个,服务器远的时候启动慢一倍多)
455
+ // 启动时的这几个平常几十毫秒就回:等 15 秒还没回就是服务器卡住了,再等一次就说(原来每个等 30 秒、重来两次)
456
+ const [, , remote] = await Promise.all([
457
+ api.get('/api/harness/me', { timeoutMs: STARTUP_TIMEOUT_MS }),
458
+ pickModel(ctx, flags.model ?? settings.model),
459
+ // 连不上服务器时下一行会报,这里就不再叠一句(原来同一个「连不上」报两遍)
460
+ api.get('/api/harness/tools', { timeoutMs: STARTUP_TIMEOUT_MS }).catch((e) => { if (e.status) ui.warn(`远程工具(Wiki / 计划 / 记忆)拿不到:${e.message}`); return []; }),
461
+ ]);
462
+ ctx.remoteTools = remote;
463
+ } catch (e) {
464
+ if (e instanceof ApiError && e.auth) { ui.error(e.message); return 1; }
465
+ throw e;
466
+ }
378
467
  }
379
468
  loadContext(ctx);
380
469
  if (flags.ephemeral) {
@@ -626,6 +715,14 @@ export async function slash(ctx, text) {
626
715
  const { ui } = ctx;
627
716
  const [cmd, ...rest] = text.split(/\s+/);
628
717
  const arg = rest.join(' ').trim();
718
+ // 直连模式下这两条要改本地配置,不走服务器(第一百二十九轮)
719
+ if (ctx.modelClient) {
720
+ const local = {
721
+ '/model': '直连模式:模型名在 ~/.zhiqu/config.json 的 direct.model 里改(或者重跑一次 zhiqu model)',
722
+ '/window': '直连模式:上下文窗口在 ~/.zhiqu/config.json 的 direct.contextWindow 里改',
723
+ }[cmd];
724
+ if (local) { ui.note(local); return null; }
725
+ }
629
726
  switch (cmd) {
630
727
  case '/exit': case '/quit': return 'exit';
631
728
  case '/help': ui.line(SLASH_HELP); return null;
@@ -668,6 +765,19 @@ export async function slash(ctx, text) {
668
765
  }
669
766
  return null;
670
767
  }
768
+ case '/agents': {
769
+ if (!ctx.agents) { ui.line('子 agent 关着(~/.zhiqu/config.json 里 agents 是 false)。'); return null; }
770
+ if (arg) {
771
+ const a = ctx.agents.get(arg);
772
+ ui.line(a ? ctx.agents.report(a) : `没有 ${arg} 这个子 agent(/agents 看有哪些)。`);
773
+ return null;
774
+ }
775
+ const list = ctx.agents.list();
776
+ if (!list.length) { ui.line('这段会话还没有派过子 agent。'); return null; }
777
+ for (const a of list) ui.line(ctx.agents.row(a));
778
+ ui.line(ui.paint.dim('/agents <编号> 看它的结论'));
779
+ return null;
780
+ }
671
781
  case '/stop': {
672
782
  if (!arg) { ui.line('要停哪个:/stop <id>,或者 /stop all(/ps 看有哪些)。'); return null; }
673
783
  const running = ctx.local.jobs.running().map((j) => j.id);
@@ -701,6 +811,7 @@ export async function slash(ctx, text) {
701
811
  return null;
702
812
  }
703
813
  case '/new':
814
+ if (ctx.agents) await ctx.agents.reset(); // 换一段会话:上一段的子 agent 不跟过来
704
815
  ctx.session = ctx.store.create({ model: ctx.model.label });
705
816
  ctx.messages = [];
706
817
  ctx.todos = [];
@@ -733,10 +844,12 @@ export async function slash(ctx, text) {
733
844
  if (spec.error) { ui.error(spec.error); return null; }
734
845
  return { review: spec };
735
846
  }
736
- case '/skills':
847
+ case '/skills': {
848
+ const label = { builtin: '内置', user: '用户', project: '项目' };
737
849
  if (!ctx.skills.length) { ui.line('没有 skill。把 SKILL.md 放进 .zhiqu/skills/<名字>/(项目级)或 ~/.zhiqu/skills/<名字>/(用户级)'); return null; }
738
- for (const s of ctx.skills) ui.line(`${s.name} ${ui.paint.dim(`(${s.source === 'project' ? '项目' : '用户'})`)} ${s.description}`);
850
+ for (const s of ctx.skills) ui.line(`${s.name} ${ui.paint.dim(`(${label[s.source] || s.source})`)} ${s.description}`);
739
851
  return null;
852
+ }
740
853
  case '/mcp': {
741
854
  const status = ctx.mcp ? ctx.mcp.status() : [];
742
855
  if (!status.length) { ui.line('没有配置 MCP 服务器。配置写在 .zhiqu/mcp.json(或 ~/.zhiqu/mcp.json)的 mcpServers 里'); return null; }
@@ -769,6 +882,7 @@ export async function slash(ctx, text) {
769
882
  }
770
883
  case '/usage': {
771
884
  ui.line(`这次会话:输入约 ${ctx.usage.prompt} token${cacheNote(ctx.usage.prompt, ctx.usage.cached)},输出约 ${ctx.usage.completion} token`);
885
+ if (!ctx.api) { ui.note('(直连模式:用量只在本地算,服务器上没有记录)'); return null; }
772
886
  try {
773
887
  const u = await ctx.api.get('/api/harness/usage');
774
888
  ui.line(`今天(命令行):${u.today.calls} 次调用,输入 ${u.today.promptTokens}${cacheNote(u.today.promptTokens, u.today.cachedTokens)}、输出 ${u.today.completionTokens} token`);
package/src/commands.js CHANGED
@@ -10,6 +10,7 @@ export const SLASH_COMMANDS = [
10
10
  { name: '/effort', args: '[instant|medium|high|extra|max]', desc: '思考档位:想得越久答得越稳,也越慢、越费 token' },
11
11
  { name: '/window', args: '[数,如 1m / 128k]', desc: '看 / 设当前模型的上下文窗口(没填就按默认 64K 算)' },
12
12
  { name: '/ps', desc: '后台在跑的命令' },
13
+ { name: '/agents', args: '[编号]', desc: '这段会话派过的子 agent:在跑 / 做完 / 停了、花了多少;给编号看它的结论' },
13
14
  { name: '/stop', args: '<id|all>', desc: '停掉后台命令(连子进程)' },
14
15
  { name: '/resume', desc: '列出这个工作区的会话,挑一段接着做' },
15
16
  { name: '/new', desc: '开一段新会话' },
package/src/config.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // <工作区>/.zhiqu/system.md 项目级系统内容,优先
7
7
  //
8
8
  // 环境变量 ZHIQU_HOME 可以把用户级目录挪走(测试用);ZHIQU_SERVER / ZHIQU_TOKEN 覆盖对应的配置。
9
+ import { agentLimits } from './subagents.js';
9
10
  import crypto from 'node:crypto';
10
11
  import fs from 'node:fs';
11
12
  import os from 'node:os';
@@ -22,8 +23,30 @@ const MODE_ALIASES = { read: 'plan', readonly: 'plan', write: 'ask', exec: 'auto
22
23
  // 思考档位(第一百零八轮,用户 2026-11-07 定的名字,网页同一套):instant 不思考,往后越想越久、越费 token。
23
24
  // 不说就听服务端的默认(app.ai.harness-reasoning)。
24
25
  export const EFFORTS = ['instant', 'medium', 'high', 'extra', 'max'];
25
- // shell 的沙箱能不能联网(第一百零九轮):默认全断,包括本机
26
+ // shell 的沙箱能不能联网(第一百零九轮):默认 on(2026-11-10 用户定的「所有人都可以联网」)。
27
+ // 原来默认全断、包括本机 —— 本机可能跑着没密码的数据库。现在默认开,想关的人用 --sandbox-network off 或用户级配置。
26
28
  export const SANDBOX_NETWORKS = ['off', 'local', 'on'];
29
+ /**
30
+ * 直连供应商(第一百二十九轮):用户自己填完整 URL,请求不经服务器。
31
+ * **只认用户级配置**(resolveSettings 里不从项目读):克隆下来的仓库不能把你的模型地址换成它的服务器,
32
+ * 那等于把代码和对话直接送出去。地址不校验格式 —— 用户明确要求「不做格式校验,直接填完整url」。
33
+ */
34
+ export function normalizeDirect(value) {
35
+ if (!value || typeof value !== 'object') return null;
36
+ const url = typeof value.url === 'string' ? value.url.trim() : '';
37
+ const model = typeof value.model === 'string' ? value.model.trim() : '';
38
+ if (!url || !model) return null; // 少了哪个都用不了,当作没配
39
+ return {
40
+ protocol: value.protocol === 'anthropic' ? 'anthropic' : 'openai',
41
+ url,
42
+ key: typeof value.key === 'string' ? value.key : '',
43
+ model,
44
+ maxTokens: Number(value.maxTokens) > 0 ? Number(value.maxTokens) : 8192,
45
+ // 直连的模型窗口服务端不知道,得自己填;不填按 64k 保守算(小了会早压缩,大了会超窗口被拒)
46
+ contextWindow: Number(value.contextWindow) > 0 ? Number(value.contextWindow) : 64_000,
47
+ };
48
+ }
49
+
27
50
  export function normalizeSandboxNetwork(value) {
28
51
  const s = String(value ?? '').trim().toLowerCase();
29
52
  return SANDBOX_NETWORKS.includes(s) ? s : null;
@@ -124,12 +147,20 @@ export function resolveSettings(root, flags = {}) {
124
147
  const mode = normalizeMode(pick('mode')) || 'ask';
125
148
  return {
126
149
  server: stripSlash(pick('server', 'ZHIQU_SERVER') || DEFAULT_SERVER),
150
+ // 服务器地址是从哪来的(第一百二十六轮 review):连不上本机时教人换,要说对改哪一处 ——
151
+ // 「zhiqu login --server」只写用户配置,地址要是从环境变量 / 项目设置来的,照着做下一次还是老地址
152
+ serverSource: flags.server != null ? 'flag' : process.env.ZHIQU_SERVER ? 'env' : project.server != null ? 'project' : user.server != null ? 'user' : 'default',
127
153
  token: process.env.ZHIQU_TOKEN || user.token || '',
128
154
  model: pick('model') ?? null,
155
+ // 直连供应商:只认用户级(见 normalizeDirect 的注释),配了就不走服务器网关、也不用登录
156
+ direct: normalizeDirect(user.direct),
129
157
  mode,
130
158
  effort: normalizeEffort(pick('effort')),
131
- // 只认命令行参数和用户级配置,不认项目里的 .zhiqu/settings.json:克隆下来的仓库不能给自己开网
132
- sandboxNetwork: normalizeSandboxNetwork(flags.sandboxNetwork ?? user.sandboxNetwork) || 'off',
159
+ // 只认命令行参数和用户级配置,不认项目里的 .zhiqu/settings.json:克隆下来的仓库不能给自己改网络档位。
160
+ // 没说就是 on(2026-11-10 用户定的);用户自己写了 off 才算关。
161
+ sandboxNetwork: normalizeSandboxNetwork(flags.sandboxNetwork ?? user.sandboxNetwork) || 'on',
162
+ // 子 agent 的开关和上限(第一百二十三轮):同样只认用户级配置 —— 克隆下来的仓库不能替用户调高花费
163
+ agents: agentLimits(user.agents),
133
164
  maxRounds: Number(project.maxRounds ?? user.maxRounds ?? 60),
134
165
  execTimeoutMs: Number(project.execTimeoutMs ?? user.execTimeoutMs ?? 120_000),
135
166
  allowedCommands: project.allowedCommands ?? user.allowedCommands ?? null,
package/src/desktop.js CHANGED
@@ -1,14 +1,11 @@
1
- // 默认连的是本机桌面应用、而它没开:macOS 上替用户把应用打开、等它起来(第十二轮)。
1
+ // 连的是本机桌面应用的地址(127.0.0.1:47615)、却连不上。
2
2
  //
3
- // 用户 2026-09-28 贴的记录里,第一次敲 zhiqu 直接「连不上服务器 http://127.0.0.1:47615(连接被拒绝…)」,还报了两遍,
4
- // 然后用户去试「知趣」这个命令(没有)、再回来重敲。桌面应用就在这台机器上,命令行完全可以自己把它打开。
5
- // 只在三件事都成立时这么做:连的是本机桌面应用的地址(回环 + 47615)、连接被拒(没在跑,不是别的错)、是 macOS。
6
- import { spawn } from 'node:child_process';
7
- import { isLoopbackUrl, LOCAL_DESKTOP_SERVER } from './defaults.js';
8
- import { sleep } from './http.js';
9
- import { monotonic } from './clock.js';
3
+ // 第十二轮起:macOS 上替用户把应用打开、等它起来(用户 2026-09-28 贴的记录里,第一次敲 zhiqu 直接「连不上服务器
4
+ // http://127.0.0.1:47615」,还报了两遍)。第一百二十五轮起 macOS 桌面版不再带后端:窗口里打开的就是网站
5
+ // (docs/desktop-remote-plan.md),本机 47615 上什么都没有 —— 再替用户打开应用只会白等 40 秒、最后说「还没起来」。
6
+ // 现在直接说清楚、给出换过去的命令。Windows 版还带着后端,这里从来不管它(照原样报「连不上」)。
7
+ import { isLoopbackUrl, LOCAL_DESKTOP_SERVER, packageDefaultServer } from './defaults.js';
10
8
 
11
- export const BUNDLE_ID = 'com.zhiqu.quadrant';
12
9
  const DESKTOP_PORT = new URL(LOCAL_DESKTOP_SERVER).port;
13
10
 
14
11
  function isDesktopServer(server) {
@@ -21,46 +18,28 @@ function isDesktopServer(server) {
21
18
 
22
19
  const isRefused = (e) => Boolean(e && e.code === 'ECONNREFUSED');
23
20
 
24
- /** `open -g -b`:按 bundle id 打开,-g 不抢终端的焦点。装了返回 true。 */
25
- export function launchApp() {
26
- return new Promise((resolve) => {
27
- const p = spawn('/usr/bin/open', ['-g', '-b', BUNDLE_ID], { stdio: 'ignore' });
28
- p.on('exit', (code) => resolve(code === 0));
29
- p.on('error', () => resolve(false));
30
- });
31
- }
32
-
33
21
  /**
34
- * 返回 'ok'(连得上 / 打开之后连上了)、'skip'(不归这里管,交给后面照常报错)、'failed'(打开不了或等不到,已经说过原因)。
22
+ * 返回 'ok'(连得上:比如旧版桌面应用还开着)、'skip'(不归这里管,交给后面照常报错)、'failed'(已经说过原因)。
35
23
  */
36
- export async function ensureLocalServer({ api, server, ui, platform = process.platform, launch = launchApp, wait = sleep, timeoutMs = 40_000 }) {
37
- if (!isDesktopServer(server) || platform !== 'darwin') return 'skip';
38
- const probe = async () => {
39
- try {
40
- await api.get('/api/harness/meta', { retry: false, timeoutMs: 3000 });
41
- return 'up';
42
- } catch (e) {
43
- return isRefused(e) ? 'down' : 'other';
44
- }
45
- };
46
- const first = await probe();
47
- if (first === 'up') return 'ok';
48
- if (first === 'other') return 'skip';
49
- ui.note('· 知趣象限桌面应用没开,正在打开它(第一次打开要几秒)…');
50
- if (!(await launch())) {
51
- ui.error('没找到知趣象限应用:先安装它(打开 dmg、拖进「应用程序」),或者用 --server 连你自己的服务器');
52
- return 'failed';
24
+ /** 怎么换到网站:地址是从哪来的就改哪一处(login 只写用户配置,环境变量、项目设置排在它前面) */
25
+ export function switchHint(source, website) {
26
+ switch (source) {
27
+ case 'env': return `地址来自环境变量 ZHIQU_SERVER:去掉它(unset ZHIQU_SERVER,shell 配置文件里的也删掉),或者改成 ${website}`;
28
+ case 'project': return `地址来自这个项目的 .zhiqu/settings.json 里的 server:删掉那一项,或者改成 ${website}`;
29
+ case 'flag': return `地址是命令行参数 --server 给的:换成 --server ${website}`;
30
+ default: return `换到网站:zhiqu login --server ${website}`;
53
31
  }
54
- const deadline = monotonic() + timeoutMs;
55
- while (monotonic() < deadline) {
56
- await wait(500);
57
- const now = await probe();
58
- if (now === 'up') {
59
- ui.note('· 桌面应用起来了');
60
- return 'ok';
61
- }
62
- if (now === 'other') return 'skip';
32
+ }
33
+
34
+ export async function ensureLocalServer({ api, server, ui, platform = process.platform, website = packageDefaultServer(), source = 'user' }) {
35
+ if (!isDesktopServer(server) || platform !== 'darwin') return 'skip';
36
+ try {
37
+ await api.get('/api/harness/meta', { retry: false, timeoutMs: 3000 });
38
+ return 'ok';
39
+ } catch (e) {
40
+ if (!isRefused(e)) return 'skip';
63
41
  }
64
- ui.error(`等了 ${Math.round(timeoutMs / 1000)} 秒桌面应用还没起来:看一眼它的窗口有没有报错(比如连不上数据库),好了再运行 zhiqu`);
42
+ ui.error(`连不上本机的 ${server}:Mac 上的知趣象限桌面应用现在打开的就是网站、不在本机跑后端了。`
43
+ + (isLoopbackUrl(website) ? '' : switchHint(source, website)));
65
44
  return 'failed';
66
45
  }