@tea-agent/loop-agent 0.39.0-next.26 → 0.39.0-next.27

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/CHANGELOG.md CHANGED
@@ -4,12 +4,16 @@
4
4
 
5
5
  ### 变更
6
6
 
7
+ - frozen repair 工具审计改为按 attempt 段扫描(B1):`session-events.jsonl` 跨 attempt 共享追加,attempt>1 的 `auditRepairAttemptToolUse` 现在只审本 attempt 字节段(newline 对齐),planner attempt 1 的 ls/find 不再被误判给 repair 轮;repair prompt 显式声明 read-only 工具契约与 allowlist 边界(B2),并内嵌 openspec-citations 输出格式正例;`LOOP_AGENT_IGNORE_STALE_DIST=1` 环境变量旁路 stale-dist guard(B3),Console spawn 的 sibling CLI 可继承。
8
+ - frontend plan/revision 结构化输出改为冻结 repair context + hash-bound canonical artifact:attempt>1 不再重放完整 planner prompt;成功后 stdout 只保留 artifact 路径,design review / prewrite 只消费已校验 artifact,不再从节点文本 merge。失败分类补齐 `structured-repair-exhausted` / `governance-blocked`,并修正 `structured-output-truncated` / `output-too-large` 的归一化映射。
7
9
  - 将 `@earendil-works/pi-ai` 与 `@earendil-works/pi-coding-agent` 从可选依赖提升为精确 pin 的运行时依赖 `0.83.0`,将运行时直接导入的 `typebox` 精确声明为 `1.3.7`,并在根包声明 Node.js `>=22.19.0`。安装 `@tea-agent/loop-agent` 会默认装上 Pi SDK(含 `--omit=optional` 场景);`@cursor/sdk` 仍保持 optional。availability / readiness 探针、隔离 tarball canary、发布包契约测试与安装/本地环境说明同步对齐。
8
10
  - backend-test Scenario Partition 仅接受绑定源有限 enum/分类集合的 GET/list query/path 轴;非法 Domain(空/重复/保留 token、无有限域、与 OpenAPI enum 不一致)报 `INVALID_PARTITION_DOMAIN` / `NO_FINITE_DOMAIN` / `PARTITION_SOURCE_MISMATCH` 根因,不再生成空后缀 `TP-SP-...-`、重复 slot,也不再级联 `MISSING_*_SLOT`。N6 对这些根因码 fail-closed;合法源分区缺槽仍阻断。N2 禁止为自由串/主键/required-only/boundary-only 建分区;N5 允许删除无源非法 Partition 及其派生槽位。
9
11
  - npm `next` 渠道发布改为提交数节流:main push 仅当距上次 next 发布的 source commit ≥ 5 个 commit 时才自动发布(新增 `scripts/next-publish-gate.mjs`,读已发布 tarball build-stamp 对比 HEAD);不足阈值时 workflow 绿色跳过,手动 `workflow_dispatch` 不受限(切 release 线前强制出包 / 紧急补发)。发布文档真源 §4.1/§5.1/§7/§12 同步。
10
12
 
11
13
  ### 新增
12
14
 
15
+ - 观察面 DAG Inspector 节点详情适配 Pi 扩展:执行器输入摘要展示节点声明的 `piExtensions` 短 id;新增「Pi 扩展运行事实」展示 `pi-extensions.json` 的 resolved(包名@版本)与 missing 降级原因(缺包降级不再静默);产物未生成/损坏时降级提示不阻断接口,绝对路径不外泄。
16
+ - 后端实现 DAG(standard / review-gated / supervised)的 Pi 节点支持按桶显式加载本机 Pi 导航扩展:读侧节点(除 closeout)加载 `pi-codegraph` + `pi-lens`,写侧节点只加载 `pi-codegraph`(pi-lens 的 `ast_grep_replace` 可绕过 writeSet,不加载);前端/测试模板与省略字段节点保持扩展全关。扩展发现始终关闭,只经白名单解析 `~/.pi/agent` 与项目 `.pi` settings 的已装包(缺包降级不失败,产物 `pi-extensions.json` 记录 requested/resolved/missing);session 后 pin 工具面剔 builtin 同名、deny 面与写工具,writer 的 `edit`/`write` 仍为 policy-wrapped;`.codegraph/**` index 同步不再计入 write-guard 越界。
13
17
  - Pi SDK 终态 session-events JSONL 顶层增加可选 `finish_reason`:仅当 `message_end` / `turn_end` / `assistant_message` 明确携带非空终止原因时由序列化层提升,不伪造默认值,也不回流 `stopReason` 诊断。
14
18
  - `backendTest` 布局配置纳入 Task Contract managed 注入面:`task advance` 新增 `--backend-test <json>`,可在公共任务生命周期内把 `testRoot`/`markdownRel`/`scriptRel`/`sharedSetupDoc`/`mode`/`gapDoc`/`executeScope` 写进 `task.json`,不再需要手工编辑(手工编辑会让任务漂移成 `externally-modified` 并拒绝 `--approve-gate`)。给出即整体替换、省略即保留既有配置(历史手写配置因此自愈)、`'{}'` 为显式清空回默认布局;重复 advance 幂等,契约保持 `managed`。`task contract diff` 把值变更标 routine `BACKEND_TEST_CONFIG_CHANGED`、丢键/清空额外标 elevated `BACKEND_TEST_CONFIG_WEAKENED`。
15
19
  - Operator Chat 文件预览抽屉新增图标「新窗口打开」:用当前已加载内容在独立浏览器窗口打开全页阅读视图,窗口内可切换「预览 / 查看原文」(带宽高的 `window.open` popup,Markdown 排版、HTML 铺满视口的空 sandbox iframe、JSON pretty-print / 其它文本等宽滚动);打开成功后断开 `opener` 且不立刻 revoke Blob,避免空白页;弹窗被拦截时 header 附近报错且不关闭抽屉
@@ -33,6 +37,7 @@
33
37
 
34
38
  ### 改进
35
39
 
40
+ - frontend DAG 的 materialized source references 恢复统一的有界 excerpt 与按需 read 指针,不再把 requirement/acceptance 文档全文复制进每个相关节点,也不再强制 contract/plan 重读全部绑定源文件,降低长需求在多节点中的重复上下文占用。
36
41
  - frontend-test prepare-package 会从 `docs/templates/`、`harness.json` `governanceRoot`/templates 以及 init 投影的 `ai_workspace/loop-agent/templates/` 拷贝标准场景;full init 目标仓不再静默落到仅含 `STD-FE-SMOKE-ENTRY` 的 fallback。
37
42
  - frontend-test 环境探测区分 connection-refused(curl 7)与 HTTP 4xx/5xx,并提示先启动本地前端后再从 probe 节点续跑;不再把所有不可达都写成同一句 `frontend-base-url-unreachable`。
38
43
  - frontend-test 报告解析用例 Markdown 的 `##`/`###` 标题与有序列表(`测试步骤` / `预期结果` / `前置条件与重置`);缺 `测试目的` 时回退到用例 H1,避免主 HTML 出现空步骤。
package/bin/loop-agent.js CHANGED
@@ -18,11 +18,15 @@ if (!existsSync(cliEntry)) {
18
18
  * to silently execute a dist/ that predates the latest source edit. The
19
19
  * classic failure mode is editing src/** and running the bin without
20
20
  * `npm run build`, which executes the previous build. Suppress with
21
- * --ignore-stale-dist when intentionally running a stale build.
21
+ * --ignore-stale-dist (or LOOP_AGENT_IGNORE_STALE_DIST=1, which sibling
22
+ * processes such as a Console-spawned CLI inherit automatically) when
23
+ * intentionally running a stale build.
22
24
  */
23
25
  const srcDir = join(packageRoot, "src");
24
- const ignoreStale = process.argv.includes("--ignore-stale-dist");
25
- if (ignoreStale) {
26
+ const ignoreStale =
27
+ process.argv.includes("--ignore-stale-dist") ||
28
+ process.env.LOOP_AGENT_IGNORE_STALE_DIST === "1";
29
+ if (process.argv.includes("--ignore-stale-dist")) {
26
30
  process.argv = process.argv.filter((arg) => arg !== "--ignore-stale-dist");
27
31
  }
28
32
  if (!ignoreStale && existsSync(srcDir)) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "version": "0.37.0",
4
- "gitSha": "261086956566acadb9df5ed94b528938cf8d058e",
5
- "builtAt": "2026-08-21T12:44:01.132Z"
4
+ "gitSha": "9c7e31bf37a0baf78e1135d61a7d5a2d97d8b8d3",
5
+ "builtAt": "2026-08-22T01:16:09.804Z"
6
6
  }
@@ -2,7 +2,8 @@ import path from "node:path";
2
2
  import { createHash } from "node:crypto";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { writeDagNodeJsonArtifact, writeTextArtifactFile, } from "../infrastructure/harness/artifact-store.js";
5
- import { executePiStep, } from "./pi-executor.js";
5
+ import { executePiStep, resolvePiBackend, } from "./pi-executor.js";
6
+ import { resolveDagPiExtensions, } from "./pi-extension-resolver.js";
6
7
  import { buildPiWriterToolPolicyContext, createPiWriterCustomTools, } from "./pi-writer-tool-policy.js";
7
8
  import { cleanupPlaywrightCliDefaultSession, createPlaywrightCliTool, PI_COMMAND_CAPABILITY_REGISTRY, resolveCaseIdFromWriteSet, resolveEvidenceDirFromWriteSet, } from "./pi-playwright-cli-tool.js";
8
9
  import { dagCommandPolicyAllows, resolveDagCommandPolicy, } from "../workflows/dag/types.js";
@@ -327,6 +328,36 @@ export async function writePiExecutorArtifacts(artifactsDir, input) {
327
328
  await writeTextArtifactFile(summaryPath, buildPiResultSummaryMarkdown(input));
328
329
  return { promptPath, summaryPath };
329
330
  }
331
+ /**
332
+ * Run-owned per-node Pi extension facts (plan 2026-08-21): requested ids,
333
+ * resolved packages (with absolute entry paths), and degraded/missing ids.
334
+ * Written only for nodes that declare `piExtensions`; never into the repo-level
335
+ * DAG template. Best-effort: artifact failures never fail the node.
336
+ */
337
+ async function writePiExtensionsArtifact(nodeArtifactsDir, requested, resolved, missing) {
338
+ try {
339
+ const runDir = path.dirname(nodeArtifactsDir);
340
+ const nodeId = path.basename(nodeArtifactsDir);
341
+ await writeDagNodeJsonArtifact(runDir, nodeId, "pi-extensions.json", {
342
+ schemaVersion: 1,
343
+ requested: [...requested],
344
+ resolved: resolved.map((entry) => ({
345
+ id: entry.id,
346
+ packageName: entry.packageName,
347
+ version: entry.version,
348
+ path: entry.entryPaths.join(", "),
349
+ })),
350
+ missing: missing.map((entry) => ({
351
+ id: entry.id,
352
+ reason: entry.reason,
353
+ ...(entry.detail ? { detail: entry.detail } : {}),
354
+ })),
355
+ });
356
+ }
357
+ catch {
358
+ // best-effort run fact; node execution continues
359
+ }
360
+ }
330
361
  async function resolveValidatedFrontendBaseUrlFromContext(workspaceRoot, runDir) {
331
362
  try {
332
363
  const capability = JSON.parse(await readFile(path.join(runDir, "preflight-frontend-browser-tool-shell", "frontend-browser-capability.json"), "utf8"));
@@ -550,6 +581,29 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
550
581
  };
551
582
  }
552
583
  }
584
+ // Plan 2026-08-21 D4/D6: resolve the node's explicit Pi extension
585
+ // allowlist against the settings inventory. Degrade on missing packages —
586
+ // never fail the node — and persist requested/resolved/missing facts.
587
+ const piExtensionsResolution = input.task.piExtensions
588
+ ? resolveDagPiExtensions({
589
+ repoRoot: input.cwd,
590
+ ids: input.task.piExtensions,
591
+ })
592
+ : undefined;
593
+ if (piExtensionsResolution) {
594
+ const piBackend = resolvePiBackend();
595
+ const cliDegraded = piBackend === "cli-only";
596
+ await writePiExtensionsArtifact(path.join(meta.runDir, input.task.id), input.task.piExtensions, cliDegraded ? [] : piExtensionsResolution.resolved, cliDegraded
597
+ ? input.task.piExtensions.map((id) => ({
598
+ id,
599
+ reason: "not-installed",
600
+ detail: "cli backend does not load pi extensions (sdk-only v1)",
601
+ }))
602
+ : piExtensionsResolution.missing);
603
+ }
604
+ const piExtensionPaths = piExtensionsResolution && resolvePiBackend() !== "cli-only"
605
+ ? piExtensionsResolution.resolved.flatMap((entry) => entry.entryPaths)
606
+ : undefined;
553
607
  result = await piStepFn({
554
608
  attachedFiles: [],
555
609
  modelConfig: resolveDagPiModelConfig(input.model, input.thinking ? { thinking: input.thinking } : undefined),
@@ -564,6 +618,9 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
564
618
  stallTimeoutMs: input.stallTimeoutMs,
565
619
  abortGraceMs: input.abortGraceMs,
566
620
  ...(writerToolPolicy ? { writerToolPolicy } : {}),
621
+ ...(piExtensionPaths && piExtensionPaths.length > 0
622
+ ? { piExtensionPaths }
623
+ : {}),
567
624
  onActivity: bridgeActivity
568
625
  ? (activity) => {
569
626
  if (activity.kind === "lease" ||
@@ -0,0 +1,233 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ /**
5
+ * Pi extension allowlist for backend implementation DAGs (plan D2/D3).
6
+ * DAG specs carry these frozen short ids; the executor resolves them against
7
+ * the Pi agent settings package inventory at run time.
8
+ */
9
+ export const DAG_PI_EXTENSION_IDS = ["pi-codegraph", "pi-lens"];
10
+ /**
11
+ * Alias table: one DAG short id may resolve to multiple published package
12
+ * names. The first settings spec whose de-`npm:`-prefixed package name is in
13
+ * the alias set wins (project settings override user settings).
14
+ */
15
+ export const DAG_PI_EXTENSION_PACKAGE_ALIASES = {
16
+ "pi-codegraph": [
17
+ "@estebanforge/pi-codegraph-enhanced",
18
+ "@vndv/pi-codegraph",
19
+ "pi-codegraph",
20
+ ],
21
+ "pi-lens": ["pi-lens"],
22
+ };
23
+ /**
24
+ * Extension tools that must never be activated as extras on any node (D5):
25
+ * they mutate files without the writer path policy. Writer nodes keep only
26
+ * policy-wrapped edit/write; read nodes keep only navigation tools.
27
+ */
28
+ export const DAG_PI_EXTENSION_WRITE_TOOL_DENY = new Set([
29
+ "ast_grep_replace",
30
+ ]);
31
+ /** Builtin tool names extensions must never replace (D5). */
32
+ export const DAG_PI_EXTENSION_PROTECTED_BUILTIN_TOOLS = new Set(["read", "edit", "write", "bash", "grep", "find", "ls"]);
33
+ /** Deny surface extensions must never activate (D5). */
34
+ export const DAG_PI_EXTENSION_DENIED_TOOL_IDS = new Set([
35
+ "apply_patch",
36
+ "apply-patch",
37
+ "full-tools",
38
+ "full_tools",
39
+ "coding-chat",
40
+ "coding_chat",
41
+ "shell",
42
+ ]);
43
+ export function isDagPiExtensionId(value) {
44
+ return DAG_PI_EXTENSION_IDS.includes(value);
45
+ }
46
+ function getPiAgentDir() {
47
+ const envDir = process.env.PI_CODING_AGENT_DIR;
48
+ if (envDir)
49
+ return envDir;
50
+ return path.join(os.homedir(), ".pi", "agent");
51
+ }
52
+ function readSettingsPackages(settingsPath) {
53
+ try {
54
+ if (!existsSync(settingsPath))
55
+ return undefined;
56
+ const parsed = JSON.parse(readFileSync(settingsPath, "utf8"));
57
+ if (!Array.isArray(parsed.packages))
58
+ return undefined;
59
+ return parsed.packages.filter((spec) => typeof spec === "string");
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
65
+ /** Strip an `npm:` prefix from a settings package spec, e.g. `npm:pi-lens`. */
66
+ export function packageNameFromSpec(spec) {
67
+ return spec.startsWith("npm:") ? spec.slice(4) : spec;
68
+ }
69
+ function loadPackageInventories(repoRoot) {
70
+ const agentDir = getPiAgentDir();
71
+ const userSpecs = readSettingsPackages(path.join(agentDir, "settings.json"));
72
+ const projectSpecs = readSettingsPackages(path.join(repoRoot, ".pi", "settings.json"));
73
+ const inventories = [];
74
+ if (userSpecs) {
75
+ inventories.push({
76
+ specs: userSpecs,
77
+ nodeModulesRoot: path.join(agentDir, "npm", "node_modules"),
78
+ });
79
+ }
80
+ if (projectSpecs) {
81
+ inventories.push({
82
+ specs: projectSpecs,
83
+ nodeModulesRoot: path.join(repoRoot, "node_modules"),
84
+ });
85
+ }
86
+ return inventories;
87
+ }
88
+ const EXTENSION_FILE_RE = /\.(?:ts|js|mjs|cjs)$/;
89
+ /**
90
+ * Resolve a package's `pi.extensions` entries to absolute entry paths.
91
+ * - A file entry maps to itself.
92
+ * - A directory entry expands to every extension file directly inside it
93
+ * (e.g. `@estebanforge/pi-codegraph-enhanced` ships `./extensions` holding
94
+ * `codegraph.ts`).
95
+ * No `pi.extensions` declaration, or a declaration whose paths do not exist,
96
+ * yields no entries (caller records `no-entry`) — no heuristic scanning
97
+ * outside declared paths.
98
+ */
99
+ export function resolvePackageEntryPaths(packageDir) {
100
+ let manifest;
101
+ try {
102
+ manifest = JSON.parse(readFileSync(path.join(packageDir, "package.json"), "utf8"));
103
+ }
104
+ catch {
105
+ return { entryPaths: [], reason: "no-entry" };
106
+ }
107
+ const declared = manifest.pi?.extensions;
108
+ if (!Array.isArray(declared)) {
109
+ return { entryPaths: [], reason: "no-entry" };
110
+ }
111
+ const entryPaths = [];
112
+ for (const entry of declared) {
113
+ if (typeof entry !== "string" || entry.length === 0)
114
+ continue;
115
+ const resolved = path.resolve(packageDir, entry);
116
+ if (!existsSync(resolved))
117
+ continue;
118
+ let isDirectory = false;
119
+ try {
120
+ isDirectory = statSync(resolved).isDirectory();
121
+ }
122
+ catch {
123
+ continue;
124
+ }
125
+ if (!isDirectory) {
126
+ entryPaths.push(resolved);
127
+ continue;
128
+ }
129
+ let names;
130
+ try {
131
+ names = readdirSync(resolved);
132
+ }
133
+ catch {
134
+ continue;
135
+ }
136
+ for (const name of names.sort()) {
137
+ if (!EXTENSION_FILE_RE.test(name))
138
+ continue;
139
+ entryPaths.push(path.join(resolved, name));
140
+ }
141
+ }
142
+ if (entryPaths.length === 0) {
143
+ return { entryPaths: [], reason: "no-entry" };
144
+ }
145
+ return { entryPaths };
146
+ }
147
+ /**
148
+ * Resolve frozen DAG short ids against the Pi settings package inventory
149
+ * (user `~/.pi/agent/settings.json`, then project `.pi/settings.json` — a
150
+ * later match on the same alias wins). Pure synchronous read; never throws.
151
+ */
152
+ export function resolveDagPiExtensions(input) {
153
+ const inventories = loadPackageInventories(input.repoRoot);
154
+ const resolved = [];
155
+ const missing = [];
156
+ for (const id of input.ids) {
157
+ if (!isDagPiExtensionId(id)) {
158
+ missing.push({
159
+ id,
160
+ reason: "package-unreadable",
161
+ detail: `unknown pi extension id: ${id}`,
162
+ });
163
+ continue;
164
+ }
165
+ const aliases = DAG_PI_EXTENSION_PACKAGE_ALIASES[id];
166
+ let matched;
167
+ // Later inventories (project) override earlier (user).
168
+ for (const inventory of inventories) {
169
+ for (const spec of inventory.specs) {
170
+ const packageName = packageNameFromSpec(spec);
171
+ if (!aliases.includes(packageName))
172
+ continue;
173
+ const packageDir = path.join(inventory.nodeModulesRoot, ...packageName.split("/"));
174
+ if (!existsSync(packageDir))
175
+ continue;
176
+ try {
177
+ const manifest = JSON.parse(readFileSync(path.join(packageDir, "package.json"), "utf8"));
178
+ if (typeof manifest.version !== "string")
179
+ continue;
180
+ matched = { packageDir, packageName, version: manifest.version };
181
+ }
182
+ catch {
183
+ // unreadable manifest: skip this candidate
184
+ }
185
+ }
186
+ }
187
+ if (!matched) {
188
+ missing.push({ id, reason: "not-installed" });
189
+ continue;
190
+ }
191
+ const entries = resolvePackageEntryPaths(matched.packageDir);
192
+ if (entries.entryPaths.length === 0) {
193
+ missing.push({
194
+ id,
195
+ reason: entries.reason === "no-entry" ? "no-entry" : "package-unreadable",
196
+ });
197
+ continue;
198
+ }
199
+ resolved.push({
200
+ id,
201
+ packageName: matched.packageName,
202
+ version: matched.version,
203
+ entryPaths: entries.entryPaths,
204
+ });
205
+ }
206
+ return { resolved, missing };
207
+ }
208
+ /**
209
+ * Compute extension tool names that may join a node's active tool allowlist
210
+ * after session creation (D5): new tool names registered by the loaded
211
+ * extensions, minus protected builtins, the deny surface, and write-capable
212
+ * extension tools (both buckets — writer writes stay policy-wrapped only).
213
+ */
214
+ export function computeExtensionToolAllowlistExtras(sessionTools, baseline) {
215
+ const baselineLower = new Set(baseline.map((name) => name.toLowerCase()));
216
+ const extras = [];
217
+ for (const tool of sessionTools) {
218
+ const name = tool && typeof tool.name === "string" ? tool.name : undefined;
219
+ if (!name)
220
+ continue;
221
+ const lower = name.toLowerCase();
222
+ if (baselineLower.has(lower))
223
+ continue;
224
+ if (DAG_PI_EXTENSION_PROTECTED_BUILTIN_TOOLS.has(lower))
225
+ continue;
226
+ if (DAG_PI_EXTENSION_DENIED_TOOL_IDS.has(lower))
227
+ continue;
228
+ if (DAG_PI_EXTENSION_WRITE_TOOL_DENY.has(lower))
229
+ continue;
230
+ extras.push(name);
231
+ }
232
+ return extras;
233
+ }
@@ -1,5 +1,6 @@
1
1
  import { appendFile, mkdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { computeExtensionToolAllowlistExtras } from "./pi-extension-resolver.js";
3
4
  import { BoundedTextPreview, classifyPiFailure, createPiJsonlStreamCollector, DEFAULT_ABORT_GRACE_MS, DEFAULT_STALL_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, extractPiEventStopReason, extractAssistantTextFromPiJson, } from "./pi-executor.js";
4
5
  import { serializeSessionEvent } from "./pi-event-serializer.js";
5
6
  import { PI_RECOMMENDED_COMPACTION, PI_RECOMMENDED_RETRY, } from "../shared/pi-retry-settings.js";
@@ -229,6 +230,9 @@ async function createSdkSession(sdk, input, shared) {
229
230
  noContextFiles: true,
230
231
  noSkills: true,
231
232
  noExtensions: true,
233
+ ...(input.additionalExtensionPaths && input.additionalExtensionPaths.length > 0
234
+ ? { additionalExtensionPaths: input.additionalExtensionPaths }
235
+ : {}),
232
236
  ...(settingsManager ? { settingsManager } : {}),
233
237
  appendSystemPromptOverride: (base) => [
234
238
  ...base,
@@ -236,6 +240,19 @@ async function createSdkSession(sdk, input, shared) {
236
240
  ],
237
241
  });
238
242
  await loader.reload();
243
+ // Discover extension-registered tool names BEFORE session creation (plan
244
+ // 2026-08-21 D5): verified against the real SDK — passing extension tool
245
+ // names in createAgentSession `tools` activates them, while a post-create
246
+ // setActiveToolsByName pin leaves the active set unchanged. Merge filtered
247
+ // extras into the create-time allowlist; protected builtins, the deny
248
+ // surface, and write-capable extension tools never join.
249
+ const extensionToolExtras = [];
250
+ if (input.additionalExtensionPaths &&
251
+ input.additionalExtensionPaths.length > 0) {
252
+ const registered = collectLoaderExtensionToolNames(loader);
253
+ extensionToolExtras.push(...computeExtensionToolAllowlistExtras(registered.map((name) => ({ name })), input.toolNames));
254
+ }
255
+ const sessionToolNames = [...input.toolNames, ...extensionToolExtras];
239
256
  if (input.requireWriterCustomTools) {
240
257
  if (!Array.isArray(input.customTools) || input.customTools.length === 0) {
241
258
  throw new Error("pi writer tool policy missing customTools; refusing to create uncontrolled writer session");
@@ -245,7 +262,7 @@ async function createSdkSession(sdk, input, shared) {
245
262
  cwd: input.cwd,
246
263
  sessionManager: SessionManager.inMemory(input.cwd),
247
264
  resourceLoader: loader,
248
- tools: input.toolNames,
265
+ tools: sessionToolNames,
249
266
  modelRuntime,
250
267
  ...(settingsManager ? { settingsManager } : {}),
251
268
  ...(model ? { model } : {}),
@@ -254,6 +271,22 @@ async function createSdkSession(sdk, input, shared) {
254
271
  ? { customTools: input.customTools }
255
272
  : {}),
256
273
  });
274
+ if (extensionToolExtras.length > 0) {
275
+ // Fail closed when merged extension tools did not activate: a silent
276
+ // pin failure must never let the node run without its declared tools.
277
+ const activeTools = created.session.agent?.state?.tools;
278
+ if (!Array.isArray(activeTools)) {
279
+ throw new Error("pi SDK session does not expose agent.state.tools; refusing unverifiable extension-tool activation");
280
+ }
281
+ const activeNames = new Set(activeTools
282
+ .map((tool) => typeof tool?.name === "string" ? tool.name : undefined)
283
+ .filter((name) => Boolean(name)));
284
+ for (const extensionToolName of extensionToolExtras) {
285
+ if (!activeNames.has(extensionToolName)) {
286
+ throw new Error(`pi SDK extension-tool activation mismatch for ${extensionToolName}: tool did not activate at session creation`);
287
+ }
288
+ }
289
+ }
257
290
  const customToolNames = (input.customTools ?? [])
258
291
  .map((tool) => isRecord(tool) && typeof tool.name === "string" ? tool.name : undefined)
259
292
  .filter((name) => Boolean(name));
@@ -266,7 +299,7 @@ async function createSdkSession(sdk, input, shared) {
266
299
  .map((tool) => typeof tool?.name === "string" ? tool.name : undefined)
267
300
  .filter((name) => Boolean(name)));
268
301
  for (const customToolName of customToolNames) {
269
- const expectedActive = input.toolNames.includes(customToolName);
302
+ const expectedActive = sessionToolNames.includes(customToolName);
270
303
  if (activeNames.has(customToolName) !== expectedActive) {
271
304
  throw new Error(`pi SDK custom-tool activation mismatch for ${customToolName}: expectedActive=${expectedActive}`);
272
305
  }
@@ -274,6 +307,47 @@ async function createSdkSession(sdk, input, shared) {
274
307
  }
275
308
  return created.session;
276
309
  }
310
+ /**
311
+ * Collect tool names registered by loader-resolved extensions. The SDK exposes
312
+ * each extension's `tools` as a Record (name → definition) or Map; both shapes
313
+ * are handled. Missing getExtensions (older SDK) yields no extras — the node
314
+ * then runs with the baseline allowlist only.
315
+ */
316
+ function collectLoaderExtensionToolNames(loader) {
317
+ const getExtensions = loader?.getExtensions;
318
+ if (typeof getExtensions !== "function")
319
+ return [];
320
+ let parsed;
321
+ try {
322
+ parsed = getExtensions.call(loader);
323
+ }
324
+ catch {
325
+ return [];
326
+ }
327
+ if (!parsed || typeof parsed !== "object")
328
+ return [];
329
+ const extensions = parsed.extensions;
330
+ if (!Array.isArray(extensions))
331
+ return [];
332
+ const names = [];
333
+ for (const extension of extensions) {
334
+ if (!extension || typeof extension !== "object")
335
+ continue;
336
+ const tools = extension.tools;
337
+ if (tools instanceof Map) {
338
+ for (const key of tools.keys()) {
339
+ if (typeof key === "string")
340
+ names.push(key);
341
+ }
342
+ }
343
+ else if (tools && typeof tools === "object") {
344
+ for (const key of Object.keys(tools)) {
345
+ names.push(key);
346
+ }
347
+ }
348
+ }
349
+ return names;
350
+ }
277
351
  /**
278
352
  * Throttle high-noise Pi SDK events from session-events.jsonl.
279
353
  * Always keeps tool lifecycle, turn/agent end, assistant messages, and errors.
@@ -545,6 +619,9 @@ export async function executeSingleSdkAttempt(options) {
545
619
  ? { customTools: writerCustomTools }
546
620
  : {}),
547
621
  ...(requireWriterCustomTools ? { requireWriterCustomTools: true } : {}),
622
+ ...(options.piExtensionPaths && options.piExtensionPaths.length > 0
623
+ ? { additionalExtensionPaths: options.piExtensionPaths }
624
+ : {}),
548
625
  });
549
626
  let resolveStall;
550
627
  let resolveSettlement;
@@ -98,6 +98,13 @@ export function isEphemeralToolCachePath(filePath) {
98
98
  const normalized = normalizePath(filePath);
99
99
  if (!normalized)
100
100
  return false;
101
+ // CodeGraph extension sync side effect (plan 2026-08-21 D7): a loaded
102
+ // pi-codegraph extension keeps an existing .codegraph/ index fresh at
103
+ // session start; those index files are extension-owned run state, not
104
+ // writer output, so they never count as write-guard violations.
105
+ if (normalized === ".codegraph" || normalized.startsWith(".codegraph/")) {
106
+ return true;
107
+ }
101
108
  if (normalized === ".pytest_cache" ||
102
109
  normalized.startsWith(".pytest_cache/")) {
103
110
  return true;
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { redactSecrets, truncateUtf8Preview } from "../../shared/preview.js";
4
4
  import { resolveDagNodeSkills } from "../../workflows/dag/skills.js";
5
- import { resolveDagNodePromptRedacted, resolveDagRunJson, } from "./dag-run-artifacts.js";
5
+ import { resolveDagNodePromptRedacted, resolveDagRunArtifact, resolveDagRunJson, } from "./dag-run-artifacts.js";
6
6
  export const NODE_INPUT_SCHEMA_VERSION = 1;
7
7
  export const NODE_INPUT_PREVIEW_MAX_BYTES = 64 * 1024;
8
8
  const SHELL_GATE_KEYS = [
@@ -33,6 +33,7 @@ function unavailableBody(dagRunId, nodeId, reason, warnings = []) {
33
33
  executorInput: null,
34
34
  boundaries: null,
35
35
  promptFingerprint: null,
36
+ piExtensionRunFacts: null,
36
37
  warnings,
37
38
  };
38
39
  }
@@ -137,7 +138,7 @@ function resolveModelHint(spec, task) {
137
138
  }
138
139
  return null;
139
140
  }
140
- function projectTask(dagRunId, nodeId, lifecycle, spec, task, fingerprint, warnings) {
141
+ function projectTask(dagRunId, nodeId, lifecycle, spec, task, fingerprint, piExtensionRunFacts, warnings) {
141
142
  const defaults = spec.defaults && typeof spec.defaults === "object"
142
143
  ? spec.defaults
143
144
  : undefined;
@@ -268,6 +269,7 @@ function projectTask(dagRunId, nodeId, lifecycle, spec, task, fingerprint, warni
268
269
  kind,
269
270
  skills,
270
271
  modelHint: resolveModelHint(spec, task),
272
+ piExtensions: redactStringList(task.piExtensions),
271
273
  shell,
272
274
  static: staticBlock,
273
275
  },
@@ -284,9 +286,72 @@ function projectTask(dagRunId, nodeId, lifecycle, spec, task, fingerprint, warni
284
286
  : null,
285
287
  },
286
288
  promptFingerprint: fingerprint,
289
+ piExtensionRunFacts,
287
290
  warnings,
288
291
  };
289
292
  }
293
+ /**
294
+ * Load run-time Pi extension facts from <node>/pi-extensions.json (plan
295
+ * 2026-08-22 R2). Returns null when the node declares no piExtensions
296
+ * (no expected artifact). Never throws: unreadable/corrupt artifacts degrade
297
+ * to parseError stubs so the node-input endpoint stays 200.
298
+ */
299
+ async function loadPiExtensionRunFacts(repoRoot, dagRunId, nodeId, declared, warnings) {
300
+ if (declared.length === 0)
301
+ return null;
302
+ const artifact = path.posix.join(nodeId, "pi-extensions.json");
303
+ const resolved = resolveDagRunArtifact(repoRoot, dagRunId, [
304
+ nodeId,
305
+ "pi-extensions.json",
306
+ ]);
307
+ if (!resolved.ok) {
308
+ if (resolved.reason === "ambiguous") {
309
+ warnings.push("Ambiguous pi-extensions.json lifecycle copies.");
310
+ }
311
+ return {
312
+ artifact,
313
+ exists: false,
314
+ requested: [...declared],
315
+ resolved: [],
316
+ missing: [],
317
+ };
318
+ }
319
+ const empty = {
320
+ artifact,
321
+ exists: false,
322
+ requested: [...declared],
323
+ resolved: [],
324
+ missing: [],
325
+ };
326
+ try {
327
+ const raw = JSON.parse(await readFile(resolved.result.absolutePath, "utf-8"));
328
+ const resolvedList = Array.isArray(raw.resolved) ? raw.resolved : [];
329
+ const missingList = Array.isArray(raw.missing) ? raw.missing : [];
330
+ const projected = resolvedList
331
+ .filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry))
332
+ .map((entry) => ({
333
+ id: redactSecrets(String(entry.id ?? "")),
334
+ packageName: redactSecrets(String(entry.packageName ?? "")),
335
+ version: redactSecrets(String(entry.version ?? "")),
336
+ }));
337
+ const missingProjected = missingList
338
+ .filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry))
339
+ .map((entry) => ({
340
+ id: redactSecrets(String(entry.id ?? "")),
341
+ reason: redactSecrets(String(entry.reason ?? "")),
342
+ }));
343
+ return {
344
+ artifact,
345
+ exists: true,
346
+ requested: redactStringList(raw.requested ?? declared),
347
+ resolved: projected,
348
+ missing: missingProjected,
349
+ };
350
+ }
351
+ catch {
352
+ return { ...empty, parseError: "read-failed" };
353
+ }
354
+ }
290
355
  async function loadPromptFingerprint(repoRoot, dagRunId, nodeId, warnings) {
291
356
  const resolved = resolveDagNodePromptRedacted(repoRoot, dagRunId, nodeId);
292
357
  if (!resolved.ok) {
@@ -415,8 +480,12 @@ export async function buildDagNodeInput(repoRoot, dagRunId, nodeId) {
415
480
  }
416
481
  const warnings = [];
417
482
  const fingerprint = await loadPromptFingerprint(repoRoot, dagRunId, nodeId, warnings);
483
+ const declaredPiExtensions = Array.isArray(task.piExtensions)
484
+ ? task.piExtensions.filter((item) => typeof item === "string")
485
+ : [];
486
+ const piExtensionRunFacts = await loadPiExtensionRunFacts(repoRoot, dagRunId, nodeId, declaredPiExtensions, warnings);
418
487
  // Reject unknown nested leakage by projecting only through allowlist helpers.
419
- const body = projectTask(dagRunId, nodeId, runResolved.result.lifecycle, spec, task, fingerprint, warnings);
488
+ const body = projectTask(dagRunId, nodeId, runResolved.result.lifecycle, spec, task, fingerprint, piExtensionRunFacts, warnings);
420
489
  // Defense-in-depth: ensure raw task never sneaks in.
421
490
  if ("task" in body) {
422
491
  return {
@@ -14,6 +14,10 @@ const ATTEMPT_FAILURE_LABELS = {
14
14
  timeout: "执行超时",
15
15
  "nonzero-exit": "命令执行失败",
16
16
  "invalid-output": "输出格式无效",
17
+ "structured-output-truncated": "结构化输出被截断",
18
+ "output-too-large": "输出超出体积上限",
19
+ "structured-repair-exhausted": "结构化修复耗尽",
20
+ "governance-blocked": "治理规则阻断",
17
21
  "empty-output": "输出为空",
18
22
  auth: "认证失败",
19
23
  quota: "额度或限流",