@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5
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/README.md +1244 -2
- package/package.json +75 -4
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +297 -0
- package/src/agent-manager.ts +1874 -0
- package/src/agent-runner.ts +1552 -0
- package/src/agent-source-badge.ts +75 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +15 -0
- package/src/clock.ts +25 -0
- package/src/completion-outbox.ts +125 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +221 -0
- package/src/custom-agents.ts +436 -0
- package/src/default-agents.ts +126 -0
- package/src/detached-results.ts +134 -0
- package/src/enabled-models.ts +180 -0
- package/src/enterprise-local.ts +66 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +148 -0
- package/src/index.ts +4423 -0
- package/src/invocation-config.ts +189 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +195 -0
- package/src/mention.ts +141 -0
- package/src/model-call.ts +83 -0
- package/src/model-resolver.ts +266 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +448 -0
- package/src/output-file.ts +164 -0
- package/src/package-resources.ts +624 -0
- package/src/prompts.ts +156 -0
- package/src/quota-admission.ts +99 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +446 -0
- package/src/settings.ts +728 -0
- package/src/skill-loader.ts +137 -0
- package/src/startup-error.ts +29 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +404 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-row.ts +235 -0
- package/src/ui/agent-widget.ts +692 -0
- package/src/ui/conversation-viewer.ts +832 -0
- package/src/ui/fleet-list.ts +675 -0
- package/src/ui/notification-view.ts +120 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +462 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +401 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +129 -0
- package/src/workflow/meta.ts +326 -0
- package/src/workflow/progress.ts +549 -0
- package/src/workflow/runtime.ts +1216 -0
- package/src/workflow/saved.ts +259 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +230 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { configuredAgentModel } from "./model-resolver.js";
|
|
5
|
+
import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The model-facing `isolation` parameter, shared by the `Agent` tool and the
|
|
9
|
+
* nested delegation tool so the two cannot drift.
|
|
10
|
+
*
|
|
11
|
+
* Shape matters more than wording here. As a single-value optional literal,
|
|
12
|
+
* models that fill every optional parameter — the transcript on #231 shows one
|
|
13
|
+
* emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
|
|
14
|
+
* had only `"worktree"` available to fill it with, and kept spawning worktrees
|
|
15
|
+
* across three turns while their own reasoning said to omit the field. Every
|
|
16
|
+
* other optional parameter has an inert filler; this one did not. `"off"` is
|
|
17
|
+
* listed first and described as the default so the harmless value is the
|
|
18
|
+
* obvious one to reach for.
|
|
19
|
+
*
|
|
20
|
+
* The wording tracks Claude Code's own `isolation` parameter, whose phrasing
|
|
21
|
+
* models have the most exposure to: one description on the union rather than
|
|
22
|
+
* per-value ones, opening "Isolation mode.", then a sentence per value in
|
|
23
|
+
* schema order, each with its caveats in a trailing parenthetical. Two clauses
|
|
24
|
+
* are ours, because our shape is not theirs — `"off"` has no counterpart there
|
|
25
|
+
* (their enum is `worktree | remote`, so both of their values do something),
|
|
26
|
+
* and neither does the uncommitted-work warning, which is the specific trap
|
|
27
|
+
* #231 fell into. Deliberately absent is any "only use a worktree when…"
|
|
28
|
+
* restriction: Claude Code's `Agent` tool states the capability and stops, and
|
|
29
|
+
* a second legal value is what lets a model decline one, not being told to.
|
|
30
|
+
*/
|
|
31
|
+
const isolationParamShape = {
|
|
32
|
+
isolation: Type.Optional(
|
|
33
|
+
Type.Union([Type.Literal("off"), Type.Literal("worktree")], {
|
|
34
|
+
description:
|
|
35
|
+
'Isolation mode. Default "off". "off" runs the agent in the current checkout, the same as omitting the field. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo (a copy cannot see uncommitted or staged changes in the main checkout).',
|
|
36
|
+
}),
|
|
37
|
+
),
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Build the `isolation` parameter for a tool schema, or nothing when the
|
|
42
|
+
* project disabled worktrees (`worktreeIsolation: false`).
|
|
43
|
+
*
|
|
44
|
+
* Dropping the field beats accepting it and quietly downgrading. The setting is
|
|
45
|
+
* for a project whose model passes `"worktree"` on *every* call, so a
|
|
46
|
+
* per-result "isolation was disabled" note would be noise on every result and
|
|
47
|
+
* would keep raising the salience of a capability that isn't there. With no
|
|
48
|
+
* field there is nothing to pass, nothing to drop, and nothing to explain — the
|
|
49
|
+
* same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
|
|
50
|
+
* cost. The resolver gate and the `agent-manager` check still cover the paths a
|
|
51
|
+
* schema can't reach: agent files, the scheduler, and cross-extension RPC.
|
|
52
|
+
*
|
|
53
|
+
* Like `scheduleParam`, this is read once at tool registration — flipping the
|
|
54
|
+
* setting needs a new pi session for the schema to change.
|
|
55
|
+
*/
|
|
56
|
+
export function isolationParam(enabled: boolean): Partial<typeof isolationParamShape> {
|
|
57
|
+
return enabled ? isolationParamShape : {};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The model-facing `cwd` parameter of the `Agent` tool.
|
|
62
|
+
*
|
|
63
|
+
* Exists because the worktree is made from the repo containing the agent's
|
|
64
|
+
* working directory, which used to always be the session cwd: a session started
|
|
65
|
+
* in `~` had no way to isolate an agent in `~/code/some-repo`.
|
|
66
|
+
*/
|
|
67
|
+
export const cwdParam = {
|
|
68
|
+
cwd: Type.Optional(
|
|
69
|
+
Type.String({
|
|
70
|
+
description:
|
|
71
|
+
'Working directory for the agent: absolute, "~/"-prefixed, or relative to the session cwd. Default: the session cwd. With isolation: "worktree", the worktree is created from the git repo containing this directory, the agent runs at the same subdirectory inside the copy, and the result branch lands in that repo. Pass it whenever the target repo is not the session cwd. Project config (.pi extensions, skills, settings) still loads from the session cwd.',
|
|
72
|
+
}),
|
|
73
|
+
),
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Resolve the `Agent` tool's `cwd` against the session cwd: `~` and `~/`
|
|
78
|
+
* expand to the home directory, a relative path resolves against `sessionCwd`.
|
|
79
|
+
* Blank means unset: models that fill every optional parameter send `""`.
|
|
80
|
+
* Existence is checked later by the manager, which re-checks at start time.
|
|
81
|
+
*/
|
|
82
|
+
export function resolveCwdParam(cwd: string | undefined, sessionCwd: string): string | undefined {
|
|
83
|
+
const trimmed = cwd?.trim();
|
|
84
|
+
if (!trimmed) return undefined;
|
|
85
|
+
// Bun 1.3 ignores HOME in os.homedir(); honor the same explicit override as Node.
|
|
86
|
+
const home = process.env[process.platform === "win32" ? "USERPROFILE" : "HOME"] || homedir();
|
|
87
|
+
if (trimmed === "~") return home;
|
|
88
|
+
if (trimmed.startsWith("~/")) return resolve(home, trimmed.slice(2));
|
|
89
|
+
return resolve(sessionCwd, trimmed);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface AgentInvocationParams {
|
|
93
|
+
model?: string;
|
|
94
|
+
thinking?: string;
|
|
95
|
+
max_turns?: number;
|
|
96
|
+
run_in_background?: boolean;
|
|
97
|
+
inherit_context?: boolean;
|
|
98
|
+
isolated?: boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Untyped on purpose. Both tool schemas now build this field conditionally
|
|
101
|
+
* and spread it, which erases TypeBox's literal inference to `unknown` (the
|
|
102
|
+
* `schedule` param has the same shape). The resolver below narrows by
|
|
103
|
+
* comparison rather than trusting the declaration, which also makes it safe
|
|
104
|
+
* for the cross-extension RPC path, where options arrive unvalidated.
|
|
105
|
+
*/
|
|
106
|
+
isolation?: unknown;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
interface ResolveOptions {
|
|
110
|
+
/** The resolved agent type, for the `agentModels` lookup. Omitted → only the `"*"` entry applies. */
|
|
111
|
+
agentType?: string;
|
|
112
|
+
/**
|
|
113
|
+
* Whether worktree isolation is permitted at all. False when the project set
|
|
114
|
+
* `worktreeIsolation: false`, which drops a requested worktree rather than
|
|
115
|
+
* failing the call: the fail-loud precedent covers spawns that *cannot* work,
|
|
116
|
+
* while this one is the user opting out, and throwing would break exactly the
|
|
117
|
+
* calls the `"off"` value exists to tolerate. Defaults to allowed.
|
|
118
|
+
*/
|
|
119
|
+
worktreeAllowed?: boolean;
|
|
120
|
+
/**
|
|
121
|
+
* What an unqualified spawn means — neither the call nor the agent file said.
|
|
122
|
+
*
|
|
123
|
+
* Top-level callers pass the `backgroundByDefault` setting (default `true`,
|
|
124
|
+
* following Claude Code). Nested callers pass `false` unconditionally: a
|
|
125
|
+
* detached child is killed by `abortOwnedChildren` when its parent settles
|
|
126
|
+
* and has no notification path of its own, so backgrounding one loses its
|
|
127
|
+
* work. Both call sites pass it explicitly; the `false` fallback only covers
|
|
128
|
+
* a caller that supplies no options at all, which in-tree means tests.
|
|
129
|
+
*/
|
|
130
|
+
defaultRunInBackground?: boolean;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function resolveAgentInvocationConfig(
|
|
134
|
+
agentConfig: AgentConfig | undefined,
|
|
135
|
+
params: AgentInvocationParams,
|
|
136
|
+
opts?: ResolveOptions,
|
|
137
|
+
): {
|
|
138
|
+
modelInput?: string;
|
|
139
|
+
modelFromParams: boolean;
|
|
140
|
+
thinking?: ThinkingLevel;
|
|
141
|
+
maxTurns?: number;
|
|
142
|
+
inheritContext: boolean;
|
|
143
|
+
runInBackground: boolean;
|
|
144
|
+
isolated: boolean;
|
|
145
|
+
isolation?: IsolationMode;
|
|
146
|
+
/**
|
|
147
|
+
* Caller thinking levels an agent file's frontmatter outranked, so surfaces
|
|
148
|
+
* can say "(asked X)" instead of presenting the effective value as requested.
|
|
149
|
+
* `model` deliberately does not behave this way: an explicit `Agent` model is
|
|
150
|
+
* an intentional dispatch choice and takes precedence over an agent default.
|
|
151
|
+
*
|
|
152
|
+
* `max_turns` is deliberately absent: no surface renders a requested-vs-
|
|
153
|
+
* effective turn limit, so recording one would be dead data.
|
|
154
|
+
*/
|
|
155
|
+
overridden?: { thinking?: ThinkingLevel };
|
|
156
|
+
} {
|
|
157
|
+
// Precedence first, collapse second — reversing these loses the veto, since
|
|
158
|
+
// an agent file's "off" only outranks a caller's "worktree" while it is still
|
|
159
|
+
// a value. Everything downstream then sees "worktree" or nothing at all.
|
|
160
|
+
const requested = agentConfig?.isolation ?? params.isolation;
|
|
161
|
+
const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : undefined;
|
|
162
|
+
|
|
163
|
+
const overriddenThinking = agentConfig?.thinking != null && params.thinking != null
|
|
164
|
+
&& agentConfig.thinking !== params.thinking
|
|
165
|
+
? params.thinking as ThinkingLevel
|
|
166
|
+
: undefined;
|
|
167
|
+
return {
|
|
168
|
+
// A frontmatter model is a portable default, not a policy boundary. An
|
|
169
|
+
// explicit model on the Agent call must win so an orchestrator can select a
|
|
170
|
+
// specific model (e.g. a `router/*` virtual model) for this dispatch. Below
|
|
171
|
+
// it, the global `agentModels` setting outranks the definition's own default.
|
|
172
|
+
modelInput: params.model ?? configuredAgentModel(opts?.agentType ?? agentConfig?.name ?? "", agentConfig?.model),
|
|
173
|
+
modelFromParams: params.model != null,
|
|
174
|
+
thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
|
|
175
|
+
maxTurns: agentConfig?.maxTurns ?? params.max_turns,
|
|
176
|
+
inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
|
|
177
|
+
runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
|
|
178
|
+
isolated: agentConfig?.isolated ?? params.isolated ?? false,
|
|
179
|
+
isolation,
|
|
180
|
+
// Undefined rather than an empty object when nothing was overridden: callers
|
|
181
|
+
// spread this into the invocation snapshot, and an always-present key would
|
|
182
|
+
// put `requestedThinking: undefined` on every record.
|
|
183
|
+
overridden: overriddenThinking ? { thinking: overriddenThinking } : undefined,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined {
|
|
188
|
+
return runInBackground ? defaultJoinMode : undefined;
|
|
189
|
+
}
|
package/src/memory.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
|
|
3
|
+
*
|
|
4
|
+
* Memory scopes:
|
|
5
|
+
* - "user" → getAgentDir()/agent-memory/{agent-name}/ (default ~/.pi/agent/agent-memory/, honors $PI_CODING_AGENT_DIR)
|
|
6
|
+
* - "project" → .pi/agent-memory/{agent-name}/
|
|
7
|
+
* - "local" → .pi/agent-memory-local/{agent-name}/
|
|
8
|
+
*
|
|
9
|
+
* The user scope previously hardcoded ~/.pi/agent-memory/. That legacy location
|
|
10
|
+
* is still honored (read + write) when it exists and the new location doesn't,
|
|
11
|
+
* so existing memories aren't orphaned.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join, } from "node:path";
|
|
17
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import type { MemoryScope } from "./types.js";
|
|
19
|
+
|
|
20
|
+
/** Maximum lines to read from MEMORY.md */
|
|
21
|
+
const MAX_MEMORY_LINES = 200;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Returns true if a name contains characters not allowed in agent/skill names.
|
|
25
|
+
* Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
|
|
26
|
+
*/
|
|
27
|
+
export function isUnsafeName(name: string): boolean {
|
|
28
|
+
if (!name || name.length > 128) return true;
|
|
29
|
+
return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Returns true if the given path is a symlink (defense against symlink attacks).
|
|
34
|
+
*/
|
|
35
|
+
export function isSymlink(filePath: string): boolean {
|
|
36
|
+
try {
|
|
37
|
+
return lstatSync(filePath).isSymbolicLink();
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Safely read a file, rejecting symlinks.
|
|
45
|
+
* Returns undefined if the file doesn't exist, is a symlink, or can't be read.
|
|
46
|
+
*/
|
|
47
|
+
export function safeReadFile(filePath: string): string | undefined {
|
|
48
|
+
if (!existsSync(filePath)) return undefined;
|
|
49
|
+
if (isSymlink(filePath)) return undefined;
|
|
50
|
+
try {
|
|
51
|
+
return readFileSync(filePath, "utf-8");
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Resolve the memory directory path for a given agent + scope + cwd.
|
|
59
|
+
* Throws if agentName contains path traversal characters.
|
|
60
|
+
*/
|
|
61
|
+
export function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string {
|
|
62
|
+
if (isUnsafeName(agentName)) {
|
|
63
|
+
throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
|
|
64
|
+
}
|
|
65
|
+
switch (scope) {
|
|
66
|
+
case "user": {
|
|
67
|
+
const current = join(getAgentDir(), "agent-memory", agentName);
|
|
68
|
+
// Legacy location from when this path was hardcoded. Keep using it if it
|
|
69
|
+
// already holds this agent's memory and the new location hasn't been
|
|
70
|
+
// created yet — otherwise existing memories would be silently orphaned.
|
|
71
|
+
const legacy = join(homedir(), ".pi", "agent-memory", agentName);
|
|
72
|
+
if (!existsSync(current) && existsSync(legacy) && !isSymlink(legacy)) {
|
|
73
|
+
return legacy;
|
|
74
|
+
}
|
|
75
|
+
return current;
|
|
76
|
+
}
|
|
77
|
+
case "project":
|
|
78
|
+
return join(cwd, ".pi", "agent-memory", agentName);
|
|
79
|
+
case "local":
|
|
80
|
+
return join(cwd, ".pi", "agent-memory-local", agentName);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Ensure the memory directory exists, creating it if needed.
|
|
86
|
+
* Refuses to create directories if any component in the path is a symlink
|
|
87
|
+
* to prevent symlink-based directory traversal attacks.
|
|
88
|
+
*/
|
|
89
|
+
export function ensureMemoryDir(memoryDir: string): void {
|
|
90
|
+
// If the directory already exists, verify it's not a symlink
|
|
91
|
+
if (existsSync(memoryDir)) {
|
|
92
|
+
if (isSymlink(memoryDir)) {
|
|
93
|
+
throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
|
|
94
|
+
}
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
mkdirSync(memoryDir, { recursive: true });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Read the first N lines of MEMORY.md from the memory directory, if it exists.
|
|
102
|
+
* Returns undefined if no MEMORY.md exists or if the path is a symlink.
|
|
103
|
+
*/
|
|
104
|
+
export function readMemoryIndex(memoryDir: string): string | undefined {
|
|
105
|
+
// Reject symlinked memory directories
|
|
106
|
+
if (isSymlink(memoryDir)) return undefined;
|
|
107
|
+
|
|
108
|
+
const memoryFile = join(memoryDir, "MEMORY.md");
|
|
109
|
+
const content = safeReadFile(memoryFile);
|
|
110
|
+
if (content === undefined) return undefined;
|
|
111
|
+
|
|
112
|
+
const lines = content.split("\n");
|
|
113
|
+
if (lines.length > MAX_MEMORY_LINES) {
|
|
114
|
+
return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
|
|
115
|
+
}
|
|
116
|
+
return content;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Build the memory block to inject into the agent's system prompt.
|
|
121
|
+
* Also ensures the memory directory exists (creates it if needed).
|
|
122
|
+
*/
|
|
123
|
+
export function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
|
|
124
|
+
const memoryDir = resolveMemoryDir(agentName, scope, cwd);
|
|
125
|
+
// Create the memory directory so the agent can immediately write to it
|
|
126
|
+
ensureMemoryDir(memoryDir);
|
|
127
|
+
|
|
128
|
+
const existingMemory = readMemoryIndex(memoryDir);
|
|
129
|
+
|
|
130
|
+
const header = `# Agent Memory
|
|
131
|
+
|
|
132
|
+
You have a persistent memory directory at: ${memoryDir}/
|
|
133
|
+
Memory scope: ${scope}
|
|
134
|
+
|
|
135
|
+
This memory persists across sessions. Use it to build up knowledge over time.`;
|
|
136
|
+
|
|
137
|
+
const memoryContent = existingMemory
|
|
138
|
+
? `\n\n## Current MEMORY.md\n${existingMemory}`
|
|
139
|
+
: `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
|
|
140
|
+
|
|
141
|
+
const instructions = `
|
|
142
|
+
|
|
143
|
+
## Memory Instructions
|
|
144
|
+
- MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
|
|
145
|
+
- Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
|
|
146
|
+
- Each memory file should use this frontmatter format:
|
|
147
|
+
\`\`\`markdown
|
|
148
|
+
---
|
|
149
|
+
name: <memory name>
|
|
150
|
+
description: <one-line description>
|
|
151
|
+
type: <user|feedback|project|reference>
|
|
152
|
+
---
|
|
153
|
+
<memory content>
|
|
154
|
+
\`\`\`
|
|
155
|
+
- Update or remove memories that become outdated. Check for existing memories before creating duplicates.
|
|
156
|
+
- You have Read, Write, and Edit tools available for managing memory files.`;
|
|
157
|
+
|
|
158
|
+
return header + memoryContent + instructions;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Build a read-only memory block for agents that lack write/edit tools.
|
|
163
|
+
* Does NOT create the memory directory — agents can only consume existing memory.
|
|
164
|
+
*/
|
|
165
|
+
export function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
|
|
166
|
+
const memoryDir = resolveMemoryDir(agentName, scope, cwd);
|
|
167
|
+
const existingMemory = readMemoryIndex(memoryDir);
|
|
168
|
+
|
|
169
|
+
const header = `# Agent Memory (read-only)
|
|
170
|
+
|
|
171
|
+
Memory scope: ${scope}
|
|
172
|
+
You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
|
|
173
|
+
|
|
174
|
+
const memoryContent = existingMemory
|
|
175
|
+
? `\n\n## Current MEMORY.md\n${existingMemory}`
|
|
176
|
+
: `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
|
|
177
|
+
|
|
178
|
+
return header + memoryContent;
|
|
179
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mention-clone.ts — start a mentioned agent through a clone of this
|
|
3
|
+
* conversation, without putting anything in the chat.
|
|
4
|
+
*
|
|
5
|
+
* Claude Code routes `@agent-<type>` through the main model: the mention
|
|
6
|
+
* becomes a `<system-reminder>` appended to the prompt and the model makes the
|
|
7
|
+
* tool call (see `agentMentionReminder`). That buys the spawned agent a prompt
|
|
8
|
+
* written with conversation context, and costs a visible turn — the model's
|
|
9
|
+
* reasoning and its tool block land in the transcript, for a decision the user
|
|
10
|
+
* already made when they typed the handle.
|
|
11
|
+
*
|
|
12
|
+
* So the turn happens somewhere else. The conversation is cloned into a
|
|
13
|
+
* throwaway in-memory session — same messages, same system prompt, same model —
|
|
14
|
+
* and that copy takes the turn off-screen. A literal clone: the session's own
|
|
15
|
+
* entries, not `inherit_context`'s text rendering of them.
|
|
16
|
+
*
|
|
17
|
+
* Pi builds every request from the session manager, so that is where the
|
|
18
|
+
* clone's history goes: the parent's root-to-leaf entries, handed to
|
|
19
|
+
* `SessionManager.inMemory`. The clone projects them itself, compaction and
|
|
20
|
+
* branch summaries included, so a long conversation clones as what the main
|
|
21
|
+
* model is actually working from. A conversation with nothing in it yet clones
|
|
22
|
+
* to nothing in it yet, which is the correct answer rather than a failure.
|
|
23
|
+
*
|
|
24
|
+
* Cloned from memory rather than from the session file, which cannot be relied
|
|
25
|
+
* on: `SessionManager._persist` withholds every write until the first assistant
|
|
26
|
+
* message lands, so a fork taken before then reads an empty file and throws.
|
|
27
|
+
*
|
|
28
|
+
* The system prompt cannot ride along in those entries. Pi rebuilds it from the
|
|
29
|
+
* session's own options on every request and patches the difference over the
|
|
30
|
+
* transcript, so the parent's prompt would be replaced by the clone's. It goes
|
|
31
|
+
* in through the resource loader's prompt override instead.
|
|
32
|
+
*
|
|
33
|
+
* Three details make the spawn belong to the real session rather than the
|
|
34
|
+
* clone:
|
|
35
|
+
*
|
|
36
|
+
* - the clone is handed the *registered* `Agent` tool, whose handler closes
|
|
37
|
+
* over the main activation, so it spawns top-level: widget, fleet row,
|
|
38
|
+
* handle, completion notification, all as if the main model had called it;
|
|
39
|
+
* - that tool is re-bound to the main `ExtensionContext`, because the handler
|
|
40
|
+
* reads `cwd`, `model` and `sessionManager.getSessionId()` off it to place
|
|
41
|
+
* the transcript and the `rootSessionId`. The clone's own context would
|
|
42
|
+
* file both under the throwaway fork;
|
|
43
|
+
* - it is called with no tool-call id. The clone's turn produces one, but the
|
|
44
|
+
* real session never issued it, and a `<tool-use-id>` pointing at nothing
|
|
45
|
+
* is exactly the bug the mention-resume path had to fix;
|
|
46
|
+
* - and it is forced into the background. A foreground agent returns its
|
|
47
|
+
* answer as the tool result and is marked `resultConsumed` so no completion
|
|
48
|
+
* notification is sent — correct when the caller is the real conversation,
|
|
49
|
+
* silent loss when the caller is a fork about to be discarded. Background
|
|
50
|
+
* delivery is the only route from a mention back to the main model.
|
|
51
|
+
*
|
|
52
|
+
* The clone gets one tool and one job. It cannot read, write or run anything —
|
|
53
|
+
* an invisible turn with the full toolset could do invisible work.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
57
|
+
import {
|
|
58
|
+
createAgentSession,
|
|
59
|
+
DefaultResourceLoader,
|
|
60
|
+
type ExtensionContext,
|
|
61
|
+
type ExtensionToolContext,
|
|
62
|
+
getAgentDir,
|
|
63
|
+
SessionManager,
|
|
64
|
+
type ToolDefinition,
|
|
65
|
+
} from "@earendil-works/pi-coding-agent";
|
|
66
|
+
import { runInChildSessionContext } from "./child-context.js";
|
|
67
|
+
import { agentMentionReminder } from "./mention.js";
|
|
68
|
+
import type { SubagentType } from "./types.js";
|
|
69
|
+
|
|
70
|
+
export interface MentionCloneOptions {
|
|
71
|
+
/** The MAIN session's context — what the spawn is attributed to, and the
|
|
72
|
+
* source of both the conversation and the live system prompt. */
|
|
73
|
+
ctx: ExtensionContext;
|
|
74
|
+
/** Agent type the handle resolved to. */
|
|
75
|
+
type: SubagentType;
|
|
76
|
+
/** What the user typed after the handle. */
|
|
77
|
+
message: string;
|
|
78
|
+
/** The registered `Agent` tool, reused so the spawn is an ordinary one. */
|
|
79
|
+
agentTool: ToolDefinition;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface MentionCloneResult {
|
|
83
|
+
/** True once the clone actually called `Agent`. */
|
|
84
|
+
spawned: boolean;
|
|
85
|
+
/** Why not, when it didn't. Absent on success. */
|
|
86
|
+
error?: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Fork the conversation, let the copy make the tool call, throw the copy away.
|
|
91
|
+
* Never rejects: a clone that cannot run is reported so the caller can fall
|
|
92
|
+
* back to starting the agent directly.
|
|
93
|
+
*/
|
|
94
|
+
export async function runMentionClone(opts: MentionCloneOptions): Promise<MentionCloneResult> {
|
|
95
|
+
const { ctx, type, message, agentTool } = opts;
|
|
96
|
+
|
|
97
|
+
let spawned = false;
|
|
98
|
+
const cloneAgentTool: ToolDefinition = {
|
|
99
|
+
...agentTool,
|
|
100
|
+
execute: (_cloneToolCallId, params, signal, onUpdate, _cloneCtx) => {
|
|
101
|
+
// One spawn per mention. The clone has a single tool and every reason to
|
|
102
|
+
// stop after using it, but a model that decides to "also" launch a second
|
|
103
|
+
// agent would do it where nobody can see and nobody asked.
|
|
104
|
+
if (spawned) {
|
|
105
|
+
return Promise.resolve({
|
|
106
|
+
content: [{ type: "text" as const, text: "Already started an agent for this mention. Stop here." }],
|
|
107
|
+
details: undefined,
|
|
108
|
+
isError: true,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
spawned = true;
|
|
112
|
+
// undefined tool-call id + the main ctx: see the header. Background is
|
|
113
|
+
// forced rather than left to the clone: `run_in_background` defaults to
|
|
114
|
+
// false, and a foreground agent answers through its TOOL RESULT — which
|
|
115
|
+
// here is delivered into a session that is disposed moments later, so the
|
|
116
|
+
// agent would run, appear in the widget and the fleet, and reach nobody.
|
|
117
|
+
return agentTool.execute(
|
|
118
|
+
undefined as never,
|
|
119
|
+
{ ...(params as Record<string, unknown>), run_in_background: true } as typeof params,
|
|
120
|
+
signal,
|
|
121
|
+
onUpdate,
|
|
122
|
+
// A tool context adds `tools` and `executeTool`, for nested tool calls;
|
|
123
|
+
// the Agent handler reads neither, only the main session's own fields.
|
|
124
|
+
ctx as ExtensionToolContext,
|
|
125
|
+
);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
|
|
130
|
+
try {
|
|
131
|
+
// Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
|
|
132
|
+
// agent-runner.ts carries the same shim for the same reason — pass both so
|
|
133
|
+
// the clone keeps the parent's providers across the supported range.
|
|
134
|
+
const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: unknown }).runtime;
|
|
135
|
+
// Absent when the session has no level of its own; the clone then takes the
|
|
136
|
+
// settings level, which is what a session that never ran `/think` is on.
|
|
137
|
+
const thinkingLevel = ctx.thinkingLevel;
|
|
138
|
+
// The live system prompt, not the one the clone would build from cwd and
|
|
139
|
+
// agentDir — extensions contribute to it per turn. Everything the loader
|
|
140
|
+
// would add on top (AGENTS.md, skills, APPEND_SYSTEM.md) is already in the
|
|
141
|
+
// rendered prompt, so it is suppressed, as agent-runner does.
|
|
142
|
+
const systemPrompt = ctx.getSystemPrompt();
|
|
143
|
+
const loader = new DefaultResourceLoader({
|
|
144
|
+
cwd: ctx.cwd,
|
|
145
|
+
agentDir: getAgentDir(),
|
|
146
|
+
noExtensions: true,
|
|
147
|
+
noSkills: true,
|
|
148
|
+
noPromptTemplates: true,
|
|
149
|
+
noThemes: true,
|
|
150
|
+
noContextFiles: true,
|
|
151
|
+
systemPromptOverride: (base: string | undefined) => systemPrompt || base,
|
|
152
|
+
appendSystemPromptOverride: () => [],
|
|
153
|
+
});
|
|
154
|
+
await runInChildSessionContext(() => loader.reload());
|
|
155
|
+
const created = await runInChildSessionContext(() =>
|
|
156
|
+
createAgentSession({
|
|
157
|
+
cwd: ctx.cwd,
|
|
158
|
+
// The parent's root-to-leaf path, which the clone projects itself:
|
|
159
|
+
// compaction applied, branch summaries substituted. Not `getEntries()`,
|
|
160
|
+
// whose last entry is not the leaf after `/tree` navigation. In memory,
|
|
161
|
+
// so nothing about the copy is persisted and the real session stays
|
|
162
|
+
// untouched.
|
|
163
|
+
sessionManager: SessionManager.inMemory(ctx.cwd, undefined, ctx.sessionManager.getBranch()),
|
|
164
|
+
resourceLoader: loader,
|
|
165
|
+
model: ctx.model as Model<never> | undefined,
|
|
166
|
+
...(thinkingLevel && { thinkingLevel }),
|
|
167
|
+
modelRegistry: ctx.modelRegistry,
|
|
168
|
+
...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime as never }),
|
|
169
|
+
// An allowlist naming exactly the clone's own tool. NOT `noTools:
|
|
170
|
+
// "all"`, whose doc comment ("start with no tools enabled") reads like
|
|
171
|
+
// it spares custom tools and does not: it resolves to an EMPTY
|
|
172
|
+
// allowlist, and `isAllowedTool` then drops every tool from the
|
|
173
|
+
// registry — the custom one included. The clone would be prompted with
|
|
174
|
+
// nothing to call, answer in prose, and every mention would fall
|
|
175
|
+
// through to the direct start with a warning. Same idiom as
|
|
176
|
+
// agent-runner's `tools: sessionTools` beside its nested `customTools`.
|
|
177
|
+
tools: [cloneAgentTool.name],
|
|
178
|
+
customTools: [cloneAgentTool],
|
|
179
|
+
} as Parameters<typeof createAgentSession>[0]),
|
|
180
|
+
);
|
|
181
|
+
session = created.session;
|
|
182
|
+
|
|
183
|
+
// User text first, reminder after — the order Claude Code's attachment
|
|
184
|
+
// renderer produces, where the reminder trails the message it is about.
|
|
185
|
+
await session.prompt(`${message}\n\n${agentMentionReminder(type)}`);
|
|
186
|
+
} catch (err) {
|
|
187
|
+
return { spawned, error: err instanceof Error ? err.message : String(err) };
|
|
188
|
+
} finally {
|
|
189
|
+
session?.dispose?.();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return spawned
|
|
193
|
+
? { spawned: true }
|
|
194
|
+
: { spawned: false, error: "the conversation clone did not start it" };
|
|
195
|
+
}
|