@gfgghgftgffg/pi-goal-x-lean 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/MAINTENANCE.md +45 -0
- package/README.md +46 -2
- package/README.zh-CN.md +47 -0
- package/delegation.ts +262 -0
- package/index.ts +79 -0
- package/integration.ts +22 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 gfgghgftgffg
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/MAINTENANCE.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Maintenance boundary
|
|
2
|
+
|
|
3
|
+
The original facade depends on exact `pi-goal-x@0.34.1`; it does not copy the engine. The published package has no npm publication `gitHead`, so maintenance reviews exact npm tarballs with SHA-512 integrity, not an inferred Git commit. There is no external lean-author repository. Pi development verification uses 1.4.0; supported hosts must satisfy upstream peers (`>=1.4.0 <2.0.0`).
|
|
4
|
+
|
|
5
|
+
## Retained behavior
|
|
6
|
+
|
|
7
|
+
Keep all eight upstream tool names, schemas except description annotations, prompt guidelines, lifecycle hooks, commands, shortcuts, renderers and tool profiles. Do not suppress `setActiveTools`, collapse names or truncate goal context: stopped-turn gates, progress classification, drafting, live-tail retention and provider-cache placement depend on them. Unknown new tools pass through unchanged until reviewed.
|
|
8
|
+
|
|
9
|
+
## Integration contracts
|
|
10
|
+
|
|
11
|
+
The optional `@gfgghgftgffg/pi-subagents-lean.context.v1` global service supplies the actual dist runner's AsyncLocalStorage child flag. Never copy child-context state, resolve an undeclared neighboring dependency or temporarily mutate `process.env`. A child registers only upstream goal-context filtering. Test the actual Pi loader and dist child-context identity; environment-marker tests alone are insufficient.
|
|
12
|
+
|
|
13
|
+
## Subagents/workflow 联动的副作用与边界
|
|
14
|
+
|
|
15
|
+
### 子会话的目标所有权
|
|
16
|
+
|
|
17
|
+
本包读取 `pi-subagents-lean` 的 v1 只读接口:父会话运行 goal,子会话只过滤继承的 goal 控制消息,不安装 goal 工具、命令或调度器。因此,子角色即使原本允许 goal,也不能用这个组合独立创建或续跑目标。角色模型、工具权限和 Task Router 规则不变,也不会自动启用 Router。
|
|
18
|
+
|
|
19
|
+
检测到 subagents manager 却没有兼容 v1 服务时,goal 门面会报兼容性错误;旧版门面、只安装原版 subagents 或其它引擎不在该自动隔离保证内。接口不是跨进程/worker 的通用检测协议,详细契约见 subagents 包的 `MAINTENANCE.md`。
|
|
20
|
+
|
|
21
|
+
### 后台等待门禁
|
|
22
|
+
|
|
23
|
+
- 仅接管 goal 为 active 时,经 `subagent(run/workflow)` 或原生 `Agent`/`SubagentWorkflow` 工具启动的委派。等待按整个父会话保守生效:任何已追踪任务未交回结果,都会挡住 goal 自动续跑和 `update_goal(status=complete)`;即使下一步与它无依赖,或已切换/新建另一个 goal,也不会自动放行。这会降低后台期间的自动推进能力。
|
|
24
|
+
- 真正投递到父会话的完成通知,或通过结果工具成功读取完整的终态 Agent 结果,才解除对应等待;“后台任务已经结束”本身不够。workflow 阶段之间暂时没有活动子 Agent,也仍视为未交回。失败/停止的终态结果同样可以解除该轮等待,但不代表 goal 验收通过。通知有延迟时会多等一段;完成验收会在工具实际执行时再次检查,避免仅靠预检放过同批启动的任务。
|
|
25
|
+
- 结果读取与 Agent `resume` 不允许并发,会返回冲突错误;请先读取结果,再在下一批工具调用中 resume。这个限制保守覆盖不同 Agent 的组合,因为句柄与 ID 可能指向同一 Agent,不能仅靠输入字符串判断。普通读取之间、全新任务启动之间不受这项限制。
|
|
26
|
+
- resume 会复用 Agent ID,因此其通知还必须匹配本轮启动的 `<tool-use-id>`;仍为 `queued`/`running` 的通知不会解除等待。缺少或不匹配轮次标记时会继续等待,可在 resume 启动返回后通过结果工具读取终态 Agent 结果,不会用旧通知推断新轮已结束。
|
|
27
|
+
- 后台任务卡住/暂停、通知丢失,或结果被外部 RPC 等未追踪入口消费并取消通知,都可能让等待一直保留。本门禁不新增超时、自行轮询或恢复调度器;Agent 的结果工具也不能读取 workflow ID 来补偿丢失的 workflow 通知。人工检查任务及 writer 状态;不要把 `/goal-resume` 或切换目标当成清除等待的方法。
|
|
28
|
+
- CLI 启动的 workflow、mention、外部 RPC、其它扩展派发,以及 goal 未 active 时就已启动的工作不受本层追踪。等待记录仅存于当前父会话内存,重载、重启或会话恢复后不重建旧记录;不能据此判断旧委派是否已经停止。
|
|
29
|
+
- 门禁不停止正在运行的任务,也不禁止用户正常输入或父 Agent 在当前轮次继续用工具。部分完成通知仍可能唤起父 Agent 处理结果,剩余任务继续阻挡自动续跑和最终完成;通知不会替用户恢复已暂停的 goal。
|
|
30
|
+
- 本适配保留 subagents 原生通知,没有把通知改写为 `pi-goal:wake`。原生通知自行触发的父模型回合不受 goal 的 `maxAutonomousRuns` 额度限制;该额度不是全部模型调用的上限。上游严格模式的 [wait/wake 协议](https://github.com/tmonk/pi-goal-x/blob/main/docs/advanced-usage.md#background-producer-integration)仍保留,但不是本门禁的默认接入方式。
|
|
31
|
+
- 门禁先于上游 `schedule` 运行,等待期间也会暂缓其中的 strict wait 截止检查;不能把 goal 的 wait deadline 当作准时超时或停止后台 writer 的保证。
|
|
32
|
+
- 维护依赖包括上游私有 `_goalCore.scheduler.schedule/claim` 及 subagents 的任务 ID、结果文本头和通知 XML 轮次标记格式。调度方法缺失时拒绝加载 goal 门面;格式变化可能漏记任务或无法解除等待,不能保证都自动报错。因此固定依赖并在升级时回归验证。这不是无需维护的原生联动。
|
|
33
|
+
|
|
34
|
+
## Additional behavior boundaries
|
|
35
|
+
|
|
36
|
+
- Goal tasks are persistent milestones; `todo` remains an independent current-turn list, with no bidirectional synchronization. Do not claim complete delegated token accounting or silently enable `strictExecutionContract`.
|
|
37
|
+
- Upstream auditing excludes project extensions by default. Enabling `auditorProjectResources` broadens resource discovery; a read-only audit policy is not an OS sandbox.
|
|
38
|
+
|
|
39
|
+
## Upstream snapshot limitation
|
|
40
|
+
|
|
41
|
+
Both the original and facade entrypoints were verified to retain the old objective after an external in-place edit and `/goal-refresh` on pi-goal-x 0.34.1; shutdown can overwrite the edit. Keep the upstream-parity regression, do not fork the storage engine to hide it, and revise the limitation when upstream fixes it. Prefer `/goal-tweak`.
|
|
42
|
+
|
|
43
|
+
## Verification
|
|
44
|
+
|
|
45
|
+
Run package type/functional tests, mixed-host discovery, fresh tool contracts and independent production installation. Integration cases cover child ownership, profile preservation, task evidence/batches, audit rejection/acceptance and notification-versus-continuation ordering without real model calls. All test homes, settings and goal pools are isolated. Tests do not justify an assertion that every upstream model/UI path was exercised.
|
package/README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-goal-x-lean
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
A lightweight wrapper over [pi-goal-x](https://github.com/tmonk/pi-goal-x): persistent goals, automatic continuation and completion auditing with shorter tool text. The upstream engine is not copied.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Keeps upstream tools, commands, UI, settings and goal-file formats.
|
|
10
|
+
- Integrates with `pi-subagents-lean` so the parent manages the goal and child sessions are identified automatically, without per-role setup.
|
|
11
|
+
- During goal execution, blocks automatic continuation and completion while background Agent/workflow work launched through `subagent` is awaiting results.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
Requires Pi `>=1.4.0 <2.0.0` and Node `>=22.19.0`. Install without a version pin:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pi install npm:@gfgghgftgffg/pi-goal-x-lean
|
|
19
|
+
pi update --extensions
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Goal works alone. For subagents integration, also run `pi install npm:@gfgghgftgffg/pi-subagents-lean`. Keep one source per extension; do not separately load upstream `pi-goal-x`.
|
|
23
|
+
|
|
24
|
+
For a Git checkout, use `node scripts/install-extension.mjs pi-goal-x-lean`.
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
/goal Add CSV export to reports, with tests and usage documentation.
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Confirm the plan to start. Use `/goal-direct` for direct creation, `/sisyphus` for ordered steps, `/goal-tweak` to revise, and `/goal-pause` / `/goal-resume` to pause or resume. See the [upstream guide](https://github.com/tmonk/pi-goal-x#readme) for all commands.
|
|
33
|
+
|
|
34
|
+
## Context footprint (character proxy)
|
|
35
|
+
|
|
36
|
+
<!-- amox-measurement:start -->
|
|
37
|
+
| Package | Registered character proxy |
|
|
38
|
+
| --- | ---: |
|
|
39
|
+
| @gfgghgftgffg/pi-goal-x-lean | 1535 |
|
|
40
|
+
| pi-goal-x | 2096 |
|
|
41
|
+
|
|
42
|
+
Fixed ceil(characters / 4), not provider billing tokens.
|
|
43
|
+
<!-- amox-measurement:end -->
|
|
44
|
+
|
|
45
|
+
## Maintenance
|
|
46
|
+
|
|
47
|
+
See [MAINTENANCE.md](MAINTENANCE.md) for integration scope, concurrency limits, side effects and upgrade checks.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# pi-goal-x-lean
|
|
2
|
+
|
|
3
|
+
[English](README.md)
|
|
4
|
+
|
|
5
|
+
[pi-goal-x](https://github.com/tmonk/pi-goal-x) 的轻量包装:保留持久目标、自动续跑和完成审计,精简工具文案,不复制上游引擎。
|
|
6
|
+
|
|
7
|
+
## 功能
|
|
8
|
+
|
|
9
|
+
- 保留上游工具、命令、界面、设置及目标文件格式。
|
|
10
|
+
- 与 `pi-subagents-lean` 联用时自动识别子会话,由父 Agent 管理目标,无需逐个角色配置。
|
|
11
|
+
- goal 执行期间,通过 `subagent` 启动的后台 Agent/workflow 未交回结果时,阻止自动续跑或完成验收。
|
|
12
|
+
|
|
13
|
+
## 安装
|
|
14
|
+
|
|
15
|
+
需要 Pi `>=1.4.0 <2.0.0`、Node `>=22.19.0`。安装时不固定版本:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pi install npm:@gfgghgftgffg/pi-goal-x-lean
|
|
19
|
+
pi update --extensions
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
单独使用 goal 不要求安装 subagents。联用时再执行 `pi install npm:@gfgghgftgffg/pi-subagents-lean`。每个扩展只保留一个来源,不再单独加载原版 `pi-goal-x`。
|
|
23
|
+
|
|
24
|
+
从 Git checkout 安装可用 `node scripts/install-extension.mjs pi-goal-x-lean`。
|
|
25
|
+
|
|
26
|
+
## 使用
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
/goal 为报表添加 CSV 导出,完成要求包括测试和使用说明
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
确认计划后开始执行。直接创建用 `/goal-direct`,有序步骤用 `/sisyphus`,修订用 `/goal-tweak`,暂停和恢复用 `/goal-pause`、`/goal-resume`。完整命令见[上游文档](https://github.com/tmonk/pi-goal-x#readme)。
|
|
33
|
+
|
|
34
|
+
## 上下文占用(字符代理)
|
|
35
|
+
|
|
36
|
+
<!-- amox-measurement:start -->
|
|
37
|
+
| Package | Registered character proxy |
|
|
38
|
+
| --- | ---: |
|
|
39
|
+
| @gfgghgftgffg/pi-goal-x-lean | 1535 |
|
|
40
|
+
| pi-goal-x | 2096 |
|
|
41
|
+
|
|
42
|
+
Fixed ceil(characters / 4), not provider billing tokens.
|
|
43
|
+
<!-- amox-measurement:end -->
|
|
44
|
+
|
|
45
|
+
## 维护
|
|
46
|
+
|
|
47
|
+
联动范围、并发限制、副作用及升级验证见 [MAINTENANCE.md](MAINTENANCE.md)。
|
package/delegation.ts
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
type Tool = ToolDefinition<any, any, any>;
|
|
4
|
+
type Goal = { id: string; status: string };
|
|
5
|
+
type Core = {
|
|
6
|
+
state: { goal: Goal | null };
|
|
7
|
+
scheduler: {
|
|
8
|
+
schedule(ctx: ExtensionContext): void;
|
|
9
|
+
claim(ctx: ExtensionContext): Record<string, unknown> | null;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
type Operation = "agent" | "workflow" | "result";
|
|
13
|
+
type Call = {
|
|
14
|
+
operation: Operation;
|
|
15
|
+
toolCallId: string;
|
|
16
|
+
resume: boolean;
|
|
17
|
+
delivered: Set<string>;
|
|
18
|
+
// A result has no generation. It may release only these exact launches,
|
|
19
|
+
// never a resume which reused their ID while the result was awaiting return.
|
|
20
|
+
holds: Map<string, Call>;
|
|
21
|
+
launches: Call[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
25
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
26
|
+
? value as Record<string, unknown> : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function operation(name: string, args: unknown): Operation | undefined {
|
|
30
|
+
if (name === "Agent") return "agent";
|
|
31
|
+
if (name === "SubagentWorkflow") return "workflow";
|
|
32
|
+
if (name === "get_subagent_result") return "result";
|
|
33
|
+
if (name !== "subagent") return;
|
|
34
|
+
// The facade routes on the outer op. JSON input supplies advanced parameters,
|
|
35
|
+
// not the operation; direct fields override that JSON. Track every run, since
|
|
36
|
+
// even a foreground Agent can be handed off to the background mid-execution.
|
|
37
|
+
switch (record(args)?.op) {
|
|
38
|
+
case "run": return "agent";
|
|
39
|
+
case "workflow": return "workflow";
|
|
40
|
+
case "result": return "result";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function id(value: unknown): value is string {
|
|
45
|
+
return typeof value === "string" && value.length > 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parameters(name: string, args: unknown): Record<string, unknown> | undefined {
|
|
49
|
+
const direct = record(args);
|
|
50
|
+
if (name !== "subagent" || typeof direct?.input !== "string") return direct;
|
|
51
|
+
try {
|
|
52
|
+
return { ...record(JSON.parse(direct.input)), ...direct };
|
|
53
|
+
} catch {
|
|
54
|
+
return direct; // The facade rejects invalid input; do not invent a launch.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function notificationCalls(content: unknown): Map<string, string> {
|
|
59
|
+
// 0.23.2 snapshots each Agent's tool-use-id in the XML body, NOT details.
|
|
60
|
+
// Batched messages contain one block per member; results are XML-escaped.
|
|
61
|
+
const text = typeof content === "string" ? content : Array.isArray(content)
|
|
62
|
+
? content.map(record).filter(part => part?.type === "text").map(part => part?.text).join("\n") : "";
|
|
63
|
+
const calls = new Map<string, string>();
|
|
64
|
+
for (const match of text.matchAll(/<task-notification>\n<task-id>([^<\r\n]+)<\/task-id>\n<tool-use-id>([^<\r\n]+)<\/tool-use-id>\n/g)) {
|
|
65
|
+
const unescape = (value: string) => value.replace(/&(amp|lt|gt);/g, (_, entity: string) =>
|
|
66
|
+
({ amp: "&", lt: "<", gt: ">" })[entity]!);
|
|
67
|
+
calls.set(match[1], unescape(match[2]));
|
|
68
|
+
}
|
|
69
|
+
return calls;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function consumedId(result: unknown): string | undefined {
|
|
73
|
+
// tintinweb 0.23.2 get_subagent_result returns NO structured details, even
|
|
74
|
+
// for saved records/handle lookups. Only its anchored, terminal result header
|
|
75
|
+
// proves consumption (running, queued, not-found and thrown waits do not).
|
|
76
|
+
const content = record(result)?.content;
|
|
77
|
+
if (!Array.isArray(content)) return;
|
|
78
|
+
const first = record(content[0]);
|
|
79
|
+
if (first?.type !== "text" || typeof first.text !== "string") return;
|
|
80
|
+
return /^Agent: ([^\r\n]+)\nType: [^\r\n]* \| Status: (?:completed|steered|aborted|stopped|error)(?: \([^\r\n]*\))? \| /.exec(first.text)?.[1];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Optional bridge for goal-x 0.34.1's _goalCore debug seam and tintinweb 0.23.2
|
|
85
|
+
* tool calls ONLY. Does not observe CLI/startup workflows, RPC or @mentions.
|
|
86
|
+
* One instance per facade/ExtensionAPI; currentSessionId must read live host
|
|
87
|
+
* state, not a session id captured at installation. Only launches made with an
|
|
88
|
+
* active goal are adopted; their holds cover the WHOLE session/workspace even
|
|
89
|
+
* after focus/create/pause. No timers, wakes or queues.
|
|
90
|
+
*/
|
|
91
|
+
export function createDelegationGuard(
|
|
92
|
+
pi: ExtensionAPI,
|
|
93
|
+
{ currentSessionId }: { currentSessionId: () => string | undefined },
|
|
94
|
+
) {
|
|
95
|
+
let core: Core | undefined;
|
|
96
|
+
let session: { id: string; manager: ExtensionContext["sessionManager"] } | undefined;
|
|
97
|
+
const calls = new Map<string, Call>();
|
|
98
|
+
const pending = new Map<string, Call>(); // asynchronous deliveries, not Agent activity
|
|
99
|
+
|
|
100
|
+
function clear(): void {
|
|
101
|
+
calls.clear();
|
|
102
|
+
pending.clear();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function current(ctx: ExtensionContext): boolean {
|
|
106
|
+
if (!session || currentSessionId() !== session.id) return false;
|
|
107
|
+
return ctx.sessionManager === session.manager && ctx.sessionManager.getSessionId() === session.id;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function hasPending(): boolean {
|
|
111
|
+
return pending.size > 0 || [...calls.values()].some(call => call.operation !== "result");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function consumedResult(taskId: string, read: Call): void {
|
|
115
|
+
const owner = pending.get(taskId);
|
|
116
|
+
if (owner && read.holds.get(taskId) === owner) pending.delete(taskId);
|
|
117
|
+
// Fresh IDs can finish before their launcher returns. Resumes cannot be
|
|
118
|
+
// credited this way: even a terminal read may have observed the OLD run.
|
|
119
|
+
for (const launch of read.launches) {
|
|
120
|
+
if (launch.resume) continue;
|
|
121
|
+
launch.delivered.add(taskId);
|
|
122
|
+
if (pending.get(taskId) === launch) pending.delete(taskId);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function notified(taskId: string, toolCallId: string | undefined): void {
|
|
127
|
+
const matches = (call: Call) => toolCallId !== undefined
|
|
128
|
+
? call.toolCallId === toolCallId : !call.resume;
|
|
129
|
+
const owner = pending.get(taskId);
|
|
130
|
+
if (owner && matches(owner)) pending.delete(taskId);
|
|
131
|
+
// Old outbox notifications survive resume. Only the matching tool-use-id
|
|
132
|
+
// proves an early notification belongs to that resume, in either end order.
|
|
133
|
+
for (const call of calls.values()) {
|
|
134
|
+
if (call.operation !== "result" && matches(call)) call.delivered.add(taskId);
|
|
135
|
+
}
|
|
136
|
+
// Do NOT schedule here. Native delivery/parent settlement owns continuation.
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
pi.on("session_start", (_event, ctx) => {
|
|
140
|
+
clear();
|
|
141
|
+
session = { id: ctx.sessionManager.getSessionId(), manager: ctx.sessionManager };
|
|
142
|
+
});
|
|
143
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
144
|
+
if (!current(ctx)) return;
|
|
145
|
+
clear();
|
|
146
|
+
session = undefined;
|
|
147
|
+
});
|
|
148
|
+
pi.on("tool_execution_start", (event, ctx) => {
|
|
149
|
+
if (!current(ctx) || !core) return;
|
|
150
|
+
const op = operation(event.toolName, event.args);
|
|
151
|
+
const goal = core.state.goal;
|
|
152
|
+
// A paused goal's result can still be consumed (and its outbox cancelled).
|
|
153
|
+
// Observe reads while holds exist, without adopting new non-goal launches.
|
|
154
|
+
if (!op || (op === "result" ? !(goal?.status === "active" || pending.size || calls.size) : goal?.status !== "active")) return;
|
|
155
|
+
const call: Call = {
|
|
156
|
+
operation: op, toolCallId: event.toolCallId,
|
|
157
|
+
resume: op === "agent" && id(parameters(event.toolName, event.args)?.resume),
|
|
158
|
+
delivered: new Set(), holds: op === "result" ? new Map(pending) : new Map(),
|
|
159
|
+
launches: op === "result" ? [...calls.values()].filter(call => call.operation !== "result" && !call.resume) : [],
|
|
160
|
+
};
|
|
161
|
+
// A read preflighted before a fresh spawn can still consume its unique ID
|
|
162
|
+
// after execution starts (e.g. a handle lookup). Preserve either ordering.
|
|
163
|
+
if (op !== "result" && !call.resume) {
|
|
164
|
+
for (const read of calls.values()) if (read.operation === "result") read.launches.push(call);
|
|
165
|
+
}
|
|
166
|
+
calls.set(event.toolCallId, call);
|
|
167
|
+
});
|
|
168
|
+
pi.on("tool_call", (event, ctx) => {
|
|
169
|
+
if (!current(ctx)) return;
|
|
170
|
+
const call = calls.get(event.toolCallId);
|
|
171
|
+
if (!call || !(call.operation === "result" || call.resume)) return;
|
|
172
|
+
// Pi preflights the whole parallel batch before executing any member. Even
|
|
173
|
+
// start order cannot distinguish an old read from a new run's consumption.
|
|
174
|
+
// Reads accept live handles/aliases, whose canonical IDs are unavailable to
|
|
175
|
+
// this bridge, so reject ALL overlapping read/resume pairs, not just equal
|
|
176
|
+
// input strings. Fresh launches and read/read batches remain unaffected.
|
|
177
|
+
if ([...calls.values()].some(other => other !== call &&
|
|
178
|
+
(call.operation === "result" ? other.resume : other.operation === "result"))) {
|
|
179
|
+
return { block: true, reason: "Cannot overlap subagent result reads with Agent resume (including handle/ID aliases). Consume the result first, then resume in a separate tool batch; read the resumed result after its launch returns." };
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
pi.on("tool_execution_end", (event, ctx) => {
|
|
183
|
+
if (!current(ctx)) return;
|
|
184
|
+
const call = calls.get(event.toolCallId);
|
|
185
|
+
if (!call) return;
|
|
186
|
+
calls.delete(event.toolCallId);
|
|
187
|
+
if (event.isError) return;
|
|
188
|
+
if (call.operation === "result") {
|
|
189
|
+
const consumed = consumedId(event.result);
|
|
190
|
+
if (consumed) consumedResult(consumed, call);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const details = record(record(event.result)?.details);
|
|
194
|
+
// Workflow is ALWAYS background. AgentDetails has status, not kind.
|
|
195
|
+
const taskId = call.operation === "workflow" ? details?.taskId
|
|
196
|
+
: details?.status === "background" ? details.agentId : undefined;
|
|
197
|
+
if (id(taskId)) {
|
|
198
|
+
// A successful resume supersedes any previous hold for the same ID.
|
|
199
|
+
pending.delete(taskId);
|
|
200
|
+
if (!call.delivered.has(taskId)) pending.set(taskId, call);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
const notification = (event: { message: unknown }, ctx: ExtensionContext): void => {
|
|
205
|
+
if (!current(ctx)) return;
|
|
206
|
+
const message = record(event.message);
|
|
207
|
+
if (message?.role !== "custom" || message.customType !== "subagent-notification") return;
|
|
208
|
+
const details = record(message.details);
|
|
209
|
+
const members = [details, ...(Array.isArray(details?.others) ? details.others.map(record) : [])];
|
|
210
|
+
const toolCalls = notificationCalls(message.content);
|
|
211
|
+
for (const member of members) {
|
|
212
|
+
// GroupJoin holds mutable Agent records: an older group can report a
|
|
213
|
+
// resumed run's new tool-use-id while that run is still queued/running.
|
|
214
|
+
if (id(member?.id) && member.status !== "queued" && member.status !== "running") {
|
|
215
|
+
notified(member.id, toolCalls.get(member.id));
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
pi.on("message_start", notification);
|
|
220
|
+
pi.on("message_end", notification);
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
/** False means the private seam is unavailable; caller must reject integration. */
|
|
224
|
+
attach(candidate: unknown): boolean {
|
|
225
|
+
if (core) return candidate === core;
|
|
226
|
+
const raw = record(candidate), state = record(raw?.state), scheduler = record(raw?.scheduler);
|
|
227
|
+
if (!state || !("goal" in state) || typeof scheduler?.schedule !== "function" || typeof scheduler.claim !== "function") return false;
|
|
228
|
+
core = candidate as Core;
|
|
229
|
+
const target = core.scheduler;
|
|
230
|
+
const schedule = target.schedule, claim = target.claim;
|
|
231
|
+
target.schedule = function (ctx) {
|
|
232
|
+
if (current(ctx) && core?.state.goal?.status === "active" && hasPending()) return;
|
|
233
|
+
return schedule.call(this, ctx);
|
|
234
|
+
};
|
|
235
|
+
target.claim = function (ctx) {
|
|
236
|
+
// Claim can be reached by a timer armed BEFORE the tool began. Block
|
|
237
|
+
// before entering it: no allowance, wait-check or generation is spent.
|
|
238
|
+
if (current(ctx) && core?.state.goal?.status === "active" && hasPending()) return null;
|
|
239
|
+
return claim.call(this, ctx);
|
|
240
|
+
};
|
|
241
|
+
return true;
|
|
242
|
+
},
|
|
243
|
+
|
|
244
|
+
/** Only update_goal.execute changes. Other tools/functions retain identity. */
|
|
245
|
+
wrapGoalTool<T extends Tool>(tool: T): T {
|
|
246
|
+
if (tool.name !== "update_goal") return tool;
|
|
247
|
+
const execute = tool.execute;
|
|
248
|
+
return {
|
|
249
|
+
...tool,
|
|
250
|
+
execute(...args: Parameters<T["execute"]>) {
|
|
251
|
+
const [, params, , , ctx] = args;
|
|
252
|
+
// tool_call may preflight an entire parallel batch before ANY execute.
|
|
253
|
+
// Check here so [workflow, complete] cannot bypass the in-flight hold.
|
|
254
|
+
if (record(params)?.status === "complete" && current(ctx) && hasPending()) {
|
|
255
|
+
throw new Error("Cannot complete goal while delegated work is pending. Wait for its completion notification or consume its full result.");
|
|
256
|
+
}
|
|
257
|
+
return execute.apply(this, args);
|
|
258
|
+
},
|
|
259
|
+
} as T;
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Keep goal-x's tool identities and lifecycle intact; only provider metadata is lean.
|
|
2
|
+
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import goal from "pi-goal-x/extensions/goal.ts";
|
|
4
|
+
import { registerGoalContext } from "pi-goal-x/extensions/goal-context.ts";
|
|
5
|
+
import { filterGoalSessionContext, isDelegatedGoalSession } from "pi-goal-x/extensions/goal-session-safety.ts";
|
|
6
|
+
import { isSubagentChild } from "./integration.ts";
|
|
7
|
+
import { createDelegationGuard } from "./delegation.ts";
|
|
8
|
+
|
|
9
|
+
const DESCRIPTIONS: Record<string, string> = {
|
|
10
|
+
create_goal: "Create and focus a persistent goal only at the user's request. mode=sisyphus follows ordered steps; token_budget caps lifetime spending, not context.",
|
|
11
|
+
get_goal: "Read goal summary; section=objective|tasks|history pages full details with cursor. task_id selects a task; verbose returns full legacy output.",
|
|
12
|
+
update_goal: "Complete (audited), block, or pause a goal; reason required for blocked/paused. Alternatively declare continuation; wait requires strictExecutionContract and a future ISO deadline. Reuse wait_id/deadline on recheck.",
|
|
13
|
+
set_goal_tasks: "Confirm a flat parent-linked task tree; matching IDs retain progress, removed IDs are deleted. block_completion defaults false. Confirmation stops the turn, then continues.",
|
|
14
|
+
update_goal_task: "Update task_id/status or ordered atomic updates; one invalid entry rejects the batch. Evidence completes contracted tasks; reason is required to skip.",
|
|
15
|
+
goal_question: "Ask one user-started drafting question. recommended is zero-based; allow_custom defaults true.",
|
|
16
|
+
goal_questionnaire: "Ask a batch of user-started drafting questions. recommended is zero-based; allow_custom defaults true.",
|
|
17
|
+
propose_goal_draft: "Confirm a draft before execution. Preserve objective for budget-only tweaks; token_budget=null removes the cap, omit retains it. auto_continue defaults true; sisyphus must match the user's mode.",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Visit schema positions only: a field named 'description' or an object-valued
|
|
21
|
+
// default/const/enum is data, not a schema annotation to discard.
|
|
22
|
+
function stripDescriptions(schema: unknown): void {
|
|
23
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) return;
|
|
24
|
+
const node = schema as Record<string, unknown>;
|
|
25
|
+
delete node.description;
|
|
26
|
+
for (const key of ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]) {
|
|
27
|
+
const map = node[key];
|
|
28
|
+
if (map && typeof map === "object") for (const child of Object.values(map)) stripDescriptions(child);
|
|
29
|
+
}
|
|
30
|
+
for (const key of ["items", "additionalProperties", "unevaluatedProperties", "contains", "propertyNames", "not", "if", "then", "else"]) {
|
|
31
|
+
const child = node[key];
|
|
32
|
+
if (Array.isArray(child)) child.forEach(stripDescriptions);
|
|
33
|
+
else stripDescriptions(child);
|
|
34
|
+
}
|
|
35
|
+
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
|
|
36
|
+
const children = node[key];
|
|
37
|
+
if (Array.isArray(children)) children.forEach(stripDescriptions);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type RegisteredTool = ToolDefinition<any, any, any>;
|
|
42
|
+
type Upstream = (pi: ExtensionAPI) => void;
|
|
43
|
+
|
|
44
|
+
export function createGoalFacade(upstream: Upstream = goal): Upstream {
|
|
45
|
+
return (pi) => {
|
|
46
|
+
if (isDelegatedGoalSession() || isSubagentChild()) {
|
|
47
|
+
registerGoalContext(pi, (messages) => filterGoalSessionContext(messages, true));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
let sessionId: string | undefined;
|
|
51
|
+
const delegation = createDelegationGuard(pi, { currentSessionId: () => sessionId });
|
|
52
|
+
pi.on("session_start", (_event, ctx) => { sessionId = ctx.sessionManager.getSessionId(); });
|
|
53
|
+
pi.on("session_shutdown", () => { sessionId = undefined; });
|
|
54
|
+
upstream(new Proxy(pi, {
|
|
55
|
+
get(target, property) {
|
|
56
|
+
if (property === "registerTool") return (tool: RegisteredTool) => {
|
|
57
|
+
// New upstream tools stay functional and unmodified until reviewed.
|
|
58
|
+
if (!Object.hasOwn(DESCRIPTIONS, tool.name)) return target.registerTool(tool);
|
|
59
|
+
const parameters = JSON.parse(JSON.stringify(tool.parameters));
|
|
60
|
+
stripDescriptions(parameters);
|
|
61
|
+
return target.registerTool(delegation.wrapGoalTool({
|
|
62
|
+
...tool,
|
|
63
|
+
description: DESCRIPTIONS[tool.name],
|
|
64
|
+
parameters,
|
|
65
|
+
promptSnippet: "",
|
|
66
|
+
// Upstream policy, validation, execution mode and renderers survive.
|
|
67
|
+
}));
|
|
68
|
+
};
|
|
69
|
+
const member = Reflect.get(target, property, target);
|
|
70
|
+
return typeof member === "function" ? member.bind(target) : member;
|
|
71
|
+
},
|
|
72
|
+
}));
|
|
73
|
+
if (!delegation.attach((pi as unknown as { _goalCore?: unknown })._goalCore)) {
|
|
74
|
+
throw new Error("pi-goal-x-lean: upstream goal scheduler integration is unavailable; review the pinned runtime before enabling goal continuation.");
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export default createGoalFacade();
|
package/integration.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const SUBAGENT_CONTEXT = Symbol.for("@gfgghgftgffg/pi-subagents-lean.context.v1");
|
|
2
|
+
const SUBAGENT_MANAGER = Symbol.for("pi-subagents:manager");
|
|
3
|
+
|
|
4
|
+
type SubagentContext = {
|
|
5
|
+
readonly version: 1;
|
|
6
|
+
readonly isChildSession: () => boolean;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
// Optional, read-only bridge: no dependency on the subagent package or its paths.
|
|
10
|
+
export function isSubagentChild(): boolean {
|
|
11
|
+
const services = globalThis as unknown as Record<symbol, unknown>;
|
|
12
|
+
const candidate = services[SUBAGENT_CONTEXT];
|
|
13
|
+
const service = candidate && typeof candidate === "object"
|
|
14
|
+
? candidate as Partial<SubagentContext> : undefined;
|
|
15
|
+
if (service?.version === 1 && typeof service.isChildSession === "function") {
|
|
16
|
+
return service.isChildSession() === true;
|
|
17
|
+
}
|
|
18
|
+
if (services[SUBAGENT_MANAGER] !== undefined) {
|
|
19
|
+
throw new Error("pi-goal-x-lean: pi-subagents manager is loaded without a compatible child-context v1 service; upgrade @gfgghgftgffg/pi-subagents-lean to >=0.1.19 when using both extensions.");
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gfgghgftgffg/pi-goal-x-lean",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Lean tool metadata over the complete pi-goal-x runtime; preserves goal tools, commands, scheduling and auditing.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"author": "gfgghgftgffg",
|
|
11
|
+
"contributors": [
|
|
12
|
+
{
|
|
13
|
+
"name": "pi-goal-x contributors",
|
|
14
|
+
"url": "https://github.com/tmonk/pi-goal-x"
|
|
15
|
+
}
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/gfgghgftgffg/amox_pi_extensions_lean.git",
|
|
20
|
+
"directory": "packages/pi-goal-x-lean"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://github.com/gfgghgftgffg/amox_pi_extensions_lean/tree/main/packages/pi-goal-x-lean#readme",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/gfgghgftgffg/amox_pi_extensions_lean/issues"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"pi-package",
|
|
28
|
+
"pi-extension",
|
|
29
|
+
"goal",
|
|
30
|
+
"token-efficient"
|
|
31
|
+
],
|
|
32
|
+
"files": [
|
|
33
|
+
"index.ts",
|
|
34
|
+
"integration.ts",
|
|
35
|
+
"delegation.ts",
|
|
36
|
+
"README.md",
|
|
37
|
+
"README.zh-CN.md",
|
|
38
|
+
"MAINTENANCE.md",
|
|
39
|
+
"LICENSE"
|
|
40
|
+
],
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=22.19.0"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"test": "node --test tests/*.test.mjs",
|
|
46
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
47
|
+
"check": "npm run typecheck && npm test"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"pi-goal-x": "0.34.1"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@earendil-works/pi-ai": ">=1.4.0 <2.0.0",
|
|
54
|
+
"@earendil-works/pi-coding-agent": ">=1.4.0 <2.0.0",
|
|
55
|
+
"@earendil-works/pi-tui": ">=1.4.0 <2.0.0",
|
|
56
|
+
"typebox": "^1.3.11"
|
|
57
|
+
},
|
|
58
|
+
"pi": {
|
|
59
|
+
"extensions": [
|
|
60
|
+
"./index.ts"
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
}
|