@trim21/personal-pi-extensions 0.1.20261017200122 → 0.1.20261017205345

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trim21/personal-pi-extensions",
3
- "version": "0.1.20261017200122",
3
+ "version": "0.1.20261017205345",
4
4
  "type": "module",
5
5
  "description": "Custom pi coding-agent extensions: bwrap sandbox, workspace guard, opencode edit, and more",
6
6
  "keywords": [
@@ -1,3 +1,3 @@
1
1
  ### AFT 工具
2
2
 
3
- 调查代码库时先用 AFT 工具(aft_outline / aft_zoom / aft_callgraph / aft_search)摸清结构、查看符号、追踪调用关系,再退回 grep 或整文件读取——它们成本更低,也是为此专门构建的。
3
+ 调查代码库时先用 AFT 工具(aft_outline / aft_zoom / aft_callgraph)摸清结构、查看符号、追踪调用关系,再退回 grep 或整文件读取——它们成本更低,也是为此专门构建的。
@@ -3,9 +3,9 @@
3
3
  在读取具体内容之前先了解文件或目录的结构。
4
4
 
5
5
  - target 为文件路径时:返回该文件的符号大纲,每个符号带签名与行号(如 `function greet(name: string): void 5:12`);Markdown/HTML 返回标题层级。适合先定位符号名和位置,再决定是否用 aft_zoom 看实现。
6
- - target 为目录路径时:默认返回扁平文件树(语言、顶层符号数、字节大小),一眼看清目录里有什么、规模多大;传 `files: false` 可切换为符号大纲(目录下每个文件的符号树,无签名,输出上限 30KB,超限截断)。
6
+ - target 为目录路径时:默认返回扁平文件树(语言、顶层符号数、字节大小),一眼看清目录里有什么、规模多大;传 `files: false` 可切换为符号大纲(目录下每个文件的符号树,无签名)。
7
7
  - `includeTests` 只在符号大纲模式(`files: false`)生效:为 true 时包含测试文件,默认排除。
8
- - 目录递归上限 200 个文件;超出部分在结果中标记截断。
8
+ - 目录遍历上限由引擎决定(当前 10000 个文件);超出部分在结果中标记截断。
9
9
  - 只接受单个 target,不支持数组;跨文件批量用多次调用。
10
10
 
11
11
  分工:看结构用本工具;看某个符号的完整源码用 aft_zoom;看符号间调用关系用 aft_callgraph。
@@ -27,8 +27,8 @@ const text = Type.String({ description: "引擎渲染的文本,与工具输出
27
27
  /** 行号区间(zoom):引擎的 Range 序列化时行号从 1 开始。 */
28
28
  const rangeSchema = Type.Object(
29
29
  {
30
- start_line: Type.Number(),
31
- end_line: Type.Number(),
30
+ start_line: Type.Optional(Type.Number()),
31
+ end_line: Type.Optional(Type.Number()),
32
32
  start_col: Type.Optional(Type.Number()),
33
33
  end_col: Type.Optional(Type.Number()),
34
34
  },
@@ -38,8 +38,8 @@ const rangeSchema = Type.Object(
38
38
  /** 调用图注解里的一条引用(zoom 的 calls_out / called_by)。 */
39
39
  const callRefSchema = Type.Object(
40
40
  {
41
- name: Type.String(),
42
- line: Type.Number(),
41
+ name: Type.Optional(Type.String()),
42
+ line: Type.Optional(Type.Number()),
43
43
  /** 同一行上还有多少条同类引用被折叠。 */
44
44
  extra_count: Type.Optional(Type.Number()),
45
45
  },
@@ -57,12 +57,12 @@ export const aftOutlineStructuredSchema = Type.Object(
57
57
  Type.Array(
58
58
  Type.Object(
59
59
  {
60
- path: Type.String(),
61
- language: Type.String(),
60
+ path: Type.Optional(Type.String()),
61
+ language: Type.Optional(Type.String()),
62
62
  /** 顶层符号数;未知时引擎省略该字段。 */
63
63
  symbols: Type.Optional(Type.Number()),
64
64
  /** 行数;null 表示不在索引里(line_count_gaps 列出这些文件)。 */
65
- lines: Type.Union([Type.Number(), Type.Null()]),
65
+ lines: Type.Optional(Type.Union([Type.Number(), Type.Null()])),
66
66
  },
67
67
  { additionalProperties: true },
68
68
  ),
package/src/aft/tools.ts CHANGED
@@ -133,7 +133,7 @@ const OutlineParams = Type.Object(
133
133
  {
134
134
  target: Type.String({
135
135
  description:
136
- "要 outline 的对象:文件路径或目录路径。只接受单个 target;目录递归上限 200 个文件。",
136
+ "要 outline 的对象:文件路径或目录路径。只接受单个 target;目录遍历上限由引擎决定(当前 10000 个文件)。",
137
137
  }),
138
138
  files: Type.Optional(
139
139
  Type.Boolean({
@@ -159,7 +159,7 @@ export function registerOutlineTool(bus: ToolBus, ctx: AftToolContext): void {
159
159
  "输出代码文件、目录的结构化大纲:函数/类/类型等符号及其行号范围;Markdown/HTML 返回标题层级。",
160
160
  "用它在读取具体内容之前先了解文件结构。",
161
161
  "深入了解某个符号用 aft_zoom;看跨文件调用关系用 aft_callgraph。",
162
- "target 支持:文件路径(带签名的符号大纲)、目录路径(递归最多 200 文件)。只接受单个 target。",
162
+ "target 支持:文件路径(带签名的符号大纲)、目录路径(遍历上限由引擎决定,当前 10000 文件)。只接受单个 target。",
163
163
  "target 为目录时默认返回扁平文件树(语言、顶层符号数、字节大小);传 files: false 可改回符号大纲。",
164
164
  ].join("\n"),
165
165
  promptSnippet: "Output structural outline of a file/directory",
@@ -191,7 +191,7 @@ export function registerOutlineTool(bus: ToolBus, ctx: AftToolContext): void {
191
191
  rawArgs,
192
192
  resolveSessionId(extCtx),
193
193
  undefined,
194
- undefined,
194
+ AFT_SOFT_CODES,
195
195
  signal,
196
196
  );
197
197
  const truncated = response.truncated === true;
@@ -274,7 +274,7 @@ export function registerZoomTool(bus: ToolBus, ctx: AftToolContext): void {
274
274
  rawArgs,
275
275
  resolveSessionId(extCtx),
276
276
  undefined,
277
- undefined,
277
+ AFT_SOFT_CODES,
278
278
  signal,
279
279
  );
280
280
  const truncated = response.truncated === true;
@@ -350,6 +350,13 @@ const CallgraphParams = Type.Object(
350
350
  { additionalProperties: false },
351
351
  );
352
352
 
353
+ /** 引擎的否定答案:这些码是一等结果,不应变成调用失败。 */
354
+ const AFT_SOFT_CODES = new Set([
355
+ "symbol_not_found",
356
+ "callgraph_building",
357
+ "search_lanes_unavailable",
358
+ ]);
359
+
353
360
  /** 只读导航的合法"否定答案":符号未定义或索引仍在构建——返回文本而非报错。 */
354
361
  const CALLGRAPH_SOFT_CODES = new Set(["symbol_not_found", "callgraph_building"]);
355
362
 
@@ -698,7 +705,7 @@ export function registerSearchTool(bus: ToolBus, ctx: AftToolContext): void {
698
705
  transportTimeoutMs: SEMANTIC_INDEX_WAIT_TIMEOUT_MS + 60_000,
699
706
  keepBridgeOnTimeout: true,
700
707
  },
701
- undefined,
708
+ AFT_SOFT_CODES,
702
709
  signal,
703
710
  ));
704
711
  } finally {
@@ -77,8 +77,8 @@ interface CallableTool {
77
77
  /** 只在 pi 有 active 工具概念时才求交(子代理、`--tools` 等场景)。 */
78
78
  function allowedToolNames(pi: ExtensionAPI): Set<string> | undefined {
79
79
  try {
80
- const active = pi.getActiveTools();
81
- return active.length > 0 ? new Set(active) : undefined;
80
+ // 空列表也是合法值(例如 --tools 排除了全部工具),不能被当成「取不到」。
81
+ return new Set(pi.getActiveTools());
82
82
  } catch {
83
83
  return undefined;
84
84
  }
@@ -114,9 +114,9 @@ function buildDescription(tools: readonly CallableTool[]): string {
114
114
  "- Do not stringify whole results (`JSON.stringify(result)`) or print every field the tool happened to",
115
115
  " return: urls, ids and metadata you will not use cost context and buy nothing.",
116
116
  "- `await sleep(seconds)` waits that many seconds (fractions allowed). It is the only way to",
117
- ' wait: the sandbox has no timers, and it beats `call("Bash", { command: "sleep 1" })`.',
117
+ " wait: the sandbox has no timers, and it beats shelling out to a tool just to sleep.",
118
118
  "- Nested calls cannot ask for user approval: a call that would need it (writing outside the",
119
- " workspace, unsandboxed Bash) fails. Make those calls directly instead of from a script.",
119
+ " workspace, unsandboxed shell) fails. Make those calls directly instead of from a script.",
120
120
  '- `// @options: {"timeout_ms": N}` bounds the whole run in milliseconds; without it the script',
121
121
  " has no time limit beyond the user aborting it.",
122
122
  "- `store.set(key, value)`, `store.get(key)` and `store.list()` are a small key/value store that",
@@ -156,9 +156,9 @@ export async function downloadReleaseAssets(
156
156
 
157
157
  const files = await listReleaseFiles(dir);
158
158
 
159
- if (files.length === 0 && params.archive === undefined) {
159
+ if (view.assets.length === 0 && params.archive === undefined) {
160
160
  return structuredFailure(
161
- `Nothing to download from ${effectiveRepo}@${view.tag_name}: the release has no assets (try archive for the source tarball). Available assets: ${assetNames.join(", ") || "(none)"}`,
161
+ `Nothing to download from ${effectiveRepo}@${view.tag_name}: the release has no assets (try archive for the source tarball).`,
162
162
  );
163
163
  }
164
164
 
@@ -27,6 +27,9 @@ import { ciLogsSchema } from "../schemas.js";
27
27
  // 缓存检查避免重复网络请求。闭包状态不与其他扩展共享,key 无需全局前缀。
28
28
  const seq = createSeqState();
29
29
 
30
+ /** GitHub 尚未开始执行的 job 状态:此时还没有日志可下载。 */
31
+ const NOT_STARTED_JOB_STATUSES = new Set(["queued", "waiting", "requested", "pending"]);
32
+
30
33
  /**
31
34
  * `OWNER/REPO` from a job's `run_url`
32
35
  * (`https://api.github.com/repos/OWNER/REPO/actions/runs/123`). The path is
@@ -375,9 +378,9 @@ async function ciLogs(gh: GhClient, call: ToolCall<JobIdParams>): Promise<CiLogs
375
378
  );
376
379
  }
377
380
 
378
- if (target.status === "queued") {
381
+ if (NOT_STARTED_JOB_STATUSES.has(target.status)) {
379
382
  return structuredFailure(
380
- `Job "${target.name}" is still queued — no logs available yet. Use \`watch-github-run\` to wait for it to start, then retry.`,
383
+ `Job "${target.name}" has not started yet (status: ${target.status}) — no logs available. Use \`watch-github-run\` to wait for it to start, then retry.`,
381
384
  );
382
385
  }
383
386
 
@@ -42,24 +42,17 @@ export function runGh(args: string[], ctx: GhRunContext): Promise<GhResult> {
42
42
  let stdout = "";
43
43
  let stderr = "";
44
44
  const combined: string[] = [];
45
- let killed = false;
46
45
  let killReason: "timeout" | "abort" | undefined;
47
46
  let timeoutId: ReturnType<typeof setTimeout> | undefined;
48
47
  let onAbort: (() => void) | undefined;
49
48
 
50
49
  const killProcess = (reason: "timeout" | "abort") => {
51
- if (killed) {
50
+ if (killReason !== undefined) {
52
51
  return;
53
52
  }
54
53
 
55
- killed = true;
56
54
  killReason = reason;
57
55
  proc.kill("SIGTERM");
58
- setTimeout(() => {
59
- if (!proc.killed) {
60
- proc.kill("SIGKILL");
61
- }
62
- }, 5000);
63
56
  };
64
57
 
65
58
  if (ctx.signal) {
@@ -106,7 +99,7 @@ export function runGh(args: string[], ctx: GhRunContext): Promise<GhResult> {
106
99
  // succeeded. -1 is a sentinel for "did not exit normally" — distinct
107
100
  // from a real gh failure exit code (1), which is always in 0-255.
108
101
  code: code ?? -1,
109
- killed,
102
+ killed: killReason !== undefined,
110
103
  combined: combined.join(""),
111
104
  reason: killReason,
112
105
  });
@@ -125,7 +118,7 @@ export function runGh(args: string[], ctx: GhRunContext): Promise<GhResult> {
125
118
  stdout,
126
119
  stderr,
127
120
  code: 1,
128
- killed,
121
+ killed: killReason !== undefined,
129
122
  combined: combined.join(""),
130
123
  reason: killReason,
131
124
  spawnError: err.message,
@@ -561,6 +561,8 @@ export function createLspService(
561
561
  const watchers = new Map<string, WorkspaceWatcher>();
562
562
  /** 因资源耗尽(ENOSPC / EMFILE)停用的监听目录;/lsp-reload 后重试。 */
563
563
  const watcherFailed = new Set<string>();
564
+ /** 已提示过监听器失败的目录:失败后重建前不重复刷屏;重建成功后移除。 */
565
+ const watcherErrorNotified = new Set<string>();
564
566
 
565
567
  /**
566
568
  * client root 的有效监听目录:root 在 cwd 内即 root;root 是 cwd 的祖先时
@@ -609,20 +611,29 @@ export function createLspService(
609
611
  notify?: ExtensionUIContext["notify"],
610
612
  ): Promise<WorkspaceWatcher | undefined> {
611
613
  const report = notify ?? sessionNotify;
614
+ // 用对象承载跨 await 的状态,避免 TS 把回调里修改的 let 收窄成字面量 false。
615
+ const watcherStatus = { startFailed: false };
612
616
  const onError = (message: string): void => {
613
- // 资源耗尽不可恢复:停用该目录直到 /lsp-reload(对齐 VS Code 对 ENOSPC 的处理)
614
- if (!/ENOSPC|EMFILE|No space left on device/i.test(message)) {
615
- report?.(message, "error");
616
- return;
617
+ watcherStatus.startFailed = true;
618
+ // 资源耗尽不可恢复:停用该目录直到 /lsp-reload(对齐 VS Code 对 ENOSPC 的处理);
619
+ // 其他失败只关闭本次监听器,下次 reconcile 仍会重建。
620
+ const exhausted = /ENOSPC|EMFILE|No space left on device/i.test(message);
621
+ if (exhausted) {
622
+ watcherFailed.add(root);
617
623
  }
618
- watcherFailed.add(root);
619
624
  const current = watchers.get(root);
620
625
  watchers.delete(root);
621
626
  void current?.stop().catch(() => {
622
627
  // 停止失败不影响流程
623
628
  });
629
+ if (watcherErrorNotified.has(root)) {
630
+ return;
631
+ }
632
+ watcherErrorNotified.add(root);
624
633
  report?.(
625
- `${message}; stopped watching ${root} until /lsp-reload (raise fs.inotify.max_user_watches first)`,
634
+ exhausted
635
+ ? `${message}; stopped watching ${root} until /lsp-reload (raise fs.inotify.max_user_watches first)`
636
+ : `${message}; stopped watching ${root}`,
626
637
  "error",
627
638
  );
628
639
  };
@@ -639,13 +650,14 @@ export function createLspService(
639
650
  "warning",
640
651
  ),
641
652
  });
642
- // 建立过程中已报不可恢复错误:直接停掉,不进监听表
643
- if (watcherFailed.has(root)) {
653
+ // 建立过程中已报错:直接停掉,不进监听表
654
+ if (watcherStatus.startFailed || watcherFailed.has(root)) {
644
655
  await watcher.stop().catch(() => {
645
656
  // 停止失败不影响流程
646
657
  });
647
658
  return undefined;
648
659
  }
660
+ watcherErrorNotified.delete(root);
649
661
  return watcher;
650
662
  } catch (error) {
651
663
  report?.(
@@ -1136,6 +1148,7 @@ export function createLspService(
1136
1148
  state.servers.clear();
1137
1149
  await stopWatchers();
1138
1150
  watcherFailed.clear();
1151
+ watcherErrorNotified.clear();
1139
1152
  updateStatusText();
1140
1153
  }
1141
1154
 
@@ -1157,6 +1170,7 @@ export function createLspService(
1157
1170
  state.brokenFailAt.clear();
1158
1171
  state.brokenNotifiedAt.clear();
1159
1172
  watcherFailed.clear();
1173
+ watcherErrorNotified.clear();
1160
1174
  updateStatusText();
1161
1175
  }
1162
1176
 
@@ -1226,6 +1240,7 @@ export function createLspService(
1226
1240
  state.disabled = false;
1227
1241
  // reload 是资源耗尽后的重试入口:清掉停用记录并按新配置重算监听范围
1228
1242
  watcherFailed.clear();
1243
+ watcherErrorNotified.clear();
1229
1244
  if (state.cwd) {
1230
1245
  await reconcileWatchers(state.cwd);
1231
1246
  }
@@ -1255,6 +1270,7 @@ export function createLspService(
1255
1270
  state.closing = false;
1256
1271
  state.disabled = false;
1257
1272
  watcherFailed.clear();
1273
+ watcherErrorNotified.clear();
1258
1274
  if (state.cwd) {
1259
1275
  await reconcileWatchers(state.cwd);
1260
1276
  }
@@ -373,12 +373,9 @@ export class ConfigAdapter implements LspServerAdapter {
373
373
 
374
374
  async spawn(root: string, cwd: string): Promise<LspServerHandle | undefined> {
375
375
  const bin = this.config.bin;
376
- if (!bin) {
377
- return undefined;
378
- }
379
376
  const setup = this.config.setup;
380
- // setup 的环境与 initializationOptionsCommand 同构(process env + 已解析 env),
381
- // 配置了 setup 时先解析 env;未配置时保持原顺序,bin 缺失不执行 env 命令。
377
+ // setup 的环境与 initializationOptionsCommand 同构(process env + 已解析 env)。
378
+ // 它无条件先执行:即使没配 bin 或 bin 解析不到,也要先跑 setup。
382
379
  let env = setup ? await resolveEnv(this.config.env, root, cwd) : undefined;
383
380
  let setupArgv: string[] | undefined;
384
381
  if (setup) {
@@ -386,6 +383,9 @@ export class ConfigAdapter implements LspServerAdapter {
386
383
  setupArgv = resolveCommandArgv(setup, root, cwd, variables);
387
384
  await runSetupCommand(setupArgv, { cwd: root, env: variables });
388
385
  }
386
+ if (!bin) {
387
+ return undefined;
388
+ }
389
389
  const resolved = await resolveBinary(bin, root, cwd);
390
390
  if (!resolved) {
391
391
  if (setupArgv) {
@@ -163,10 +163,10 @@ export function extractFirstUserPrompt(
163
163
  ): string | undefined {
164
164
  const trimmed = currentPrompt.trim();
165
165
  for (const entry of branch) {
166
- if (entry.type !== "message") {
166
+ if (entry.type !== "message" || entry.message?.role !== "user") {
167
167
  continue;
168
168
  }
169
- const text = messageText(entry.message?.content);
169
+ const text = messageText(entry.message.content);
170
170
  if (text) {
171
171
  return text;
172
172
  }
@@ -300,10 +300,11 @@ export async function callVision(
300
300
 
301
301
  /** 视觉代理工具集(未配置视觉模型时返回 undefined):入口从它取注册函数。 */
302
302
  export function createVisionTools(): ToolModule | undefined {
303
- // 未配置视觉模型就不注册工具:agent 看不到也调不到。provider 的
304
- // baseUrl/apiKey 由 pi 的模型注册表在调用时解析(execute 里 find),
305
- // 配置好 settings.json / models.json 后重新加载(/reload)即可生效。
306
- if (!loadVisionConfig()?.model) {
303
+ // 未配置 provider 或 model 就不注册工具:agent 看不到也调不到,避免出现必然失败的
304
+ // 僵尸工具。provider 的 baseUrl/apiKey 由 pi 的模型注册表在调用时解析(execute 里
305
+ // find),配置好 settings.json / models.json 后重新加载(/reload)即可生效。
306
+ const config = loadVisionConfig();
307
+ if (!config?.provider || !config.model) {
307
308
  return undefined;
308
309
  }
309
310
  return {
package/src/web/fetch.ts CHANGED
@@ -141,12 +141,14 @@ async function fetchWithRedirects(
141
141
  signal: AbortSignal | undefined,
142
142
  fetchFn: typeof fetch = egress.fetch,
143
143
  ): Promise<{ response: Response; url: URL }> {
144
+ // 30 秒预算覆盖整次抓取(含所有重定向跳),不是每跳重新计时。
145
+ const timeoutSignal = withTimeoutSignal(signal, TIMEOUT_MS);
144
146
  let current = url;
145
147
  for (let redirects = 0; ; redirects++) {
146
148
  await assertPublicHostname(current.hostname);
147
149
  const response = await fetchFn(current, {
148
150
  redirect: "manual",
149
- signal: withTimeoutSignal(signal, TIMEOUT_MS),
151
+ signal: timeoutSignal,
150
152
  headers: { "user-agent": "Mozilla/5.0 (compatible; pi-web-fetch/1.0)" },
151
153
  });
152
154
  const location = response.headers.get("location");