pi-jar 0.2.1 → 0.2.2
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/README.md +2 -2
- package/docs/EFFICIENCY_PLAN.md +59 -0
- package/docs/WORKFLOWS.md +1 -1
- package/extensions/index.ts +1 -1
- package/package.json +1 -1
- package/src/advisor.ts +1 -1
- package/src/delegate.ts +20 -5
- package/src/goal-loop.ts +8 -22
- package/src/perf.ts +21 -4
- package/src/plan.ts +8 -23
- package/src/profiles.ts +2 -1
- package/src/side-model.ts +14 -0
- package/src/workflow-context.ts +37 -0
package/README.md
CHANGED
|
@@ -269,14 +269,14 @@ This is a pi-jar enhancement: [pi-advisor](https://github.com/philipbrembeck/pi-
|
|
|
269
269
|
- **Context diet (opt-in)** — `/jar settings` → **Pi** → **Context diet (prior-turn reasoning)**. Saved independently per profile; OFF by default. Removes eligible thinking blocks from completed earlier user turns only in outgoing context, never from stored history. Current reasoning signatures, user requests, tool arguments/results, and workflow state remain intact; ambiguous tool chains are left unchanged. Opaque signature character counts are diagnostics, not token savings. Existing SoL-Pi observation packing remains responsible for tool-result projection.
|
|
270
270
|
- **`jar_shell`** — `start` (optional `name`, `watch` regex, `notify`, task/service `purpose`), `list`, `peek`, bounded `wait`, `output`, `kill`. ANSI-stripped logs have per-job caps and a 4 MiB aggregate budget; surfaced finished jobs compact to a 32 KiB tail. Live jobs retain useful tails and are never killed to reclaim logs. Watch/exit notifications are compact and coalesced; reads acknowledge observed events. Active model responses cannot be interrupted by a completion event: the UI previews status without consuming it, and model delivery waits for a safe boundary. When no useful work remains, use bounded `wait` for the relevant finite jobs rather than waiting for an automatic wake-up. Each running shell gets a footer row and an activity view (`/jar shells`) with `x` kill and `f` follow. All shells stop when the session ends.
|
|
271
271
|
- **`jar_delegate`** — spawns retained, session-scoped subagents up to **Max subagents** in `/jar settings` (2, 4, 6, 8 or 16; default 4). Idle, paused and hibernated agents count toward this pool; over-cap batches are rejected. `scout` is fresh/read-only, `fork` inherits conversation read-only, and `worktree` forks context into a path-guarded Git worktree. Settled retained agents close their Pi process after 30 seconds of quiet while keeping their private session and workspace; `resume`/`ask` relaunch that same session. Launch returns before startup or the first turn completes, including legacy one-shot `write: true` mode.
|
|
272
|
-
- **`jar_subagent`** — `peek` reports progress, including the workspace path and changed files for recovery records; `steer` redirects a running worker; `resume` relaunches an idle/paused/hibernated agent. `ask`, `pause` and `stop` return accepted receipts immediately; answers and final handoffs arrive as `pi-jar.subagent` events. `stop` reconciles safe worktree changes; conflicts remain private and can be retried with `stop` after resolving parent drift. `discard` removes an unresolved recovery worktree without applying it. At most four active/recovery worktrees are admitted; resolve or discard one before starting another. Session shutdown reports paths of any preserved worktrees. Controls do not poll the child.
|
|
272
|
+
- **`jar_subagent`** — `peek` reports progress, including the workspace path and changed files for recovery records; `steer` redirects a running worker; `resume` relaunches an idle/paused/hibernated agent; `report` returns an agent's latest full report (a synchronous `jar_delegate` result shares a 16k-character report budget across its runs and points here when it truncates). `ask`, `pause` and `stop` return accepted receipts immediately; answers and final handoffs arrive as `pi-jar.subagent` events. `stop` reconciles safe worktree changes; conflicts remain private and can be retried with `stop` after resolving parent drift. `discard` removes an unresolved recovery worktree without applying it. At most four active/recovery worktrees are admitted; resolve or discard one before starting another. Session shutdown reports paths of any preserved worktrees. Controls do not poll the child.
|
|
273
273
|
- **Subagent capabilities** — each task can set `tools` or `inheritTools: true`; known-tool mode filters and child guards remain in force. See [tool capabilities](docs/SUBAGENT-TOOLS.md).
|
|
274
274
|
- **Worktree finalization** — edits do not touch the parent merely because a worker settles or hibernates. On `jar_subagent stop`, pi-jar checks parent drift and reviewability, applies safe changes and adds them to `/diff`; conflicts remain isolated for retry or explicit discard. Failed worktree transcripts are compacted independently of finished history. Process closure is awaited before finalization, and failed multi-file application rolls back rather than leaving a partial result.
|
|
275
275
|
- **`jar_democracy`** — **exceptional only**, for a persistent super-complex issue with several evidence-backed options after at least two distinct failed approaches. The moderator opens 2–8 options, resumes relevant idle/paused/hibernated fresh-context read-only scouts or spawns new scouts within the pool, and collects one private ballot per voter. A strict majority of invited voters wins; ties, plurality or missing/invalid ballots require user choice. Voting never implements its recommendation. A round has a 10-minute deadline and bounded rationales.
|
|
276
276
|
- **`jar_discuss`** — session-local, parent-owned discussion broker over authenticated local IPC; no shared paper, lock or polling. `ask`/`answer` return stable IDs without echoing your text. `list` reads only relevant unread questions/answers and advances your cursor; `thread` (or `list` with `questionId`) reads one thread; `pending` shows counts without message bodies. `since: "d0"` rereads relevant mail. At most 128 messages, 1600 characters each and 128 KiB are retained; unread/unanswered questions block new posts instead of being silently lost. Messages do not wake idle agents; the next natural turn gets an unread notice.
|
|
277
277
|
- **Activity view** — one split view (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>A</kbd>, `/jar activity`, or a click on a footer row) for subagents, background shells and other extensions' teammates: list on the left, live details on the right (auto-follows; scroll up to pause, `f` to follow again). For a subagent the details show its task, its own checklist with subtasks, and a transcript like omp's: each tool call and message is one collapsed line that expands on demand (`Tab` into it, `↑↓`, `Enter`, or click) to show arguments and output, while streaming text shows live. `s` opens a steering input: type a message and press `Enter` to redirect the running subagent. `x` stops just that one. Finished runs stay listed for review.
|
|
278
278
|
- **`/jar history`** — separate, read-only timeline of the active branch (paging, search, expandable details). Pi's native transcript is untouched.
|
|
279
|
-
- Pi's built-in read/shell/edit/write tool cards render compactly: collapsed, each is one padded, state-colored card with its call line and a one-line summary (edit included), and partially streamed arguments never flicker to a fallback; the full output or diff stays one click or <kbd>Ctrl</kbd>+<kbd>O</kbd> away. Every requested frame re-renders the whole transcript, so background sources (subagent streams, shell changes, context and cost updates) share one adaptive repaint budget: at most every 250 ms below 300 branch entries, 500 ms below 800, 1 s below 2,000, and only on visible state changes beyond that; a frame Pi draws on its own satisfies pending updates. User actions and state changes (a subagent or shell starting, settling or failing) still repaint at once. The open activity view repaints live updates every 100 ms, slowing to 500 ms in very large sessions. Context usage is cached: session start, tree navigation, compaction, model changes, renames and the end of a run refresh it at once, while message ends recompute it at most every 750 ms. `/jar perf` shows the counters. The sliding bar some terminals show in the tab while the agent works is Pi's own `OSC 9;4` progress (`terminal.showTerminalProgress` in Pi settings), not pi-jar.
|
|
279
|
+
- Pi's built-in read/shell/edit/write tool cards render compactly: collapsed, each is one padded, state-colored card with its call line and a one-line summary (edit included), and partially streamed arguments never flicker to a fallback; the full output or diff stays one click or <kbd>Ctrl</kbd>+<kbd>O</kbd> away. Every requested frame re-renders the whole transcript, so background sources (subagent streams, shell changes, context and cost updates) share one adaptive repaint budget: at most every 250 ms below 300 branch entries, 500 ms below 800, 1 s below 2,000, and only on visible state changes beyond that; a frame Pi draws on its own satisfies pending updates. User actions and state changes (a subagent or shell starting, settling or failing) still repaint at once. The open activity view repaints live updates every 100 ms, slowing to 500 ms in very large sessions. Context usage is cached: session start, tree navigation, compaction, model changes, renames and the end of a run refresh it at once, while message ends recompute it at most every 750 ms, widening up to 5 s when the measured computation is slow so sampling stays near a 1% duty cycle. `/jar perf` shows the counters. The sliding bar some terminals show in the tab while the agent works is Pi's own `OSC 9;4` progress (`terminal.showTerminalProgress` in Pi settings), not pi-jar.
|
|
280
280
|
|
|
281
281
|
## Settings
|
|
282
282
|
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Efficiency Plan
|
|
2
|
+
|
|
3
|
+
## Status
|
|
4
|
+
|
|
5
|
+
Triaged against the 0.2.1 codebase and partly implemented in v0.2.2. Most of the original proposal was either already shipped by the long-session work ([LONG_SESSION_PERFORMANCE_PLAN.md](./LONG_SESSION_PERFORMANCE_PLAN.md), 0.1.9–0.2.1) or costs more in complexity and risk than it saves. Only items with a measurable win and no behavior change were taken.
|
|
6
|
+
|
|
7
|
+
## Goal
|
|
8
|
+
|
|
9
|
+
Keep long sessions fast and cheap without losing stored history or changing what the model sees unless the user opted in.
|
|
10
|
+
|
|
11
|
+
## Implemented in 0.2.2
|
|
12
|
+
|
|
13
|
+
### Adaptive context sampling (was item 8)
|
|
14
|
+
|
|
15
|
+
`ContextSampler` (`src/perf.ts`) now widens its mid-turn throttle from the measured cost of `getContextUsage()` instead of a fixed 750 ms: the window is `max(750 ms, 100 × median sample time)`, capped at 5 s. Mid-turn sampling therefore stays near a 1% duty cycle whatever the session size; cheap sessions keep the 750 ms cadence, and lifecycle boundaries (start, tree, compact, model, rename, settle) still refresh immediately. Measured cost is used rather than entry-count tiers because it is the quantity being bounded and needs no extra wiring. `/jar perf` shows the current window.
|
|
16
|
+
|
|
17
|
+
### Profile pin lookup without a copy (part of item 9)
|
|
18
|
+
|
|
19
|
+
`pinnedProfileId` walks the branch backwards in place instead of allocating `[...entries].reverse()`. `conversationStarted` already exits at the first user message, so it needed no change; neither runs per frame, so no incremental cache was added.
|
|
20
|
+
|
|
21
|
+
### Cache-stable workflow prompts (follow-up)
|
|
22
|
+
|
|
23
|
+
Plan and goal prompts used to be pruned to the newest copy on every call. Removing an earlier copy changes the conversation prefix, so each new turn (or goal round) re-sent the whole previous run uncached. `src/workflow-context.ts` now projects them so that every keep/drop decision depends only on earlier messages: identical plan/goal context is sent once, sent reminders and continuations stay in place, and leaving the mode drops them all once. It runs on Pi's message list before provider conversion, so it helps every provider that caches by prefix (Anthropic explicit breakpoints, OpenAI/DeepSeek/Gemini automatic prefix caching, Bedrock). Appending the context at the tail was rejected: pi-ai places the Anthropic cache breakpoint on the last message, so a moving tail would defeat the cache entirely.
|
|
24
|
+
|
|
25
|
+
### Unset side roles are visible (follow-up)
|
|
26
|
+
|
|
27
|
+
`askRole` notifies once per role when an unassigned role (advisor, commit, …) ran on the current main model, with the `/roles set` command to fix it. Behaviour is unchanged.
|
|
28
|
+
|
|
29
|
+
### Bounded synchronous subagent results (follow-up)
|
|
30
|
+
|
|
31
|
+
A synchronous `jar_delegate` result shares a 16k-character report budget across its runs (at least 2k each) instead of up to 12k per run. Truncated reports name `jar_subagent report <key>`, a new read-only action returning the full stored report. Event messages were already capped at 1.2k.
|
|
32
|
+
|
|
33
|
+
### Cheaper subagent subscriber (follow-up)
|
|
34
|
+
|
|
35
|
+
The footer's per-tick registry listener reads `DelegateRegistry.stateSignature()` straight from the map instead of `records()` (a second sweep, a sort and two arrays per 50 ms tick).
|
|
36
|
+
|
|
37
|
+
## Already covered — dropped
|
|
38
|
+
|
|
39
|
+
| Item | Why |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| 5. Tier subagent events | Already tiered: tool `onUpdate` ≤ 1 s, footer status only on state change, key/state changes are `transition` and everything else `background` in `RenderScheduler` (250 ms–1 s by session size, transitions-only beyond), Activity view coalesces at 100–500 ms. The 50 ms stream tick only feeds that scheduler. |
|
|
42
|
+
| 6. Footer snapshot | `renderFooterLayout` already memoizes on a key of width/theme/view; repaints between changes are cache hits. A versioned snapshot would need change notifications from every source for a microsecond saving. |
|
|
43
|
+
| 7. Bounded advisor fingerprints | `callKey` already keeps a 200-char prefix plus a SHA-1 of large inputs, so the loop window never pins large payloads. Prefix/suffix-only hashing would let distinct writes collide and trigger false loop alerts. |
|
|
44
|
+
|
|
45
|
+
## Deferred
|
|
46
|
+
|
|
47
|
+
| Item | Why |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| 1. Single Context Projector | The four `context` hooks (child automation filter, diet, plan, goal) are each one `customType` scan that allocates only when something is stale — negligible next to request serialization. Merging them couples independent modules for no measurable gain. Revisit only if `/jar perf` shows context hooks in a profile. |
|
|
50
|
+
| 2. Context Diet v2 (`stripper` model, `DietSnapshot`) | A model-written summary replaces exact history with a lossy one, adds a side call per compression and duplicates Pi's own compaction. Needs its own design (fidelity, resumability, cache-hit impact) before code. |
|
|
51
|
+
| 3. Diet-aware delegation | Depends on item 2. Today `scout` already starts fresh and `fork` is an explicit mode; changing the defaults alters subagent results. |
|
|
52
|
+
| 4. Strict utility roles | Side calls without a role use the current model by design (`askRole`); making them fail or go deterministic breaks advisor and commit messages for users without roles. Addressed instead by the one-time notice above. |
|
|
53
|
+
| 10. Compact workflow history | Rewriting persisted session history is ruled out; provider context is handled by the cache-stable projection above. |
|
|
54
|
+
|
|
55
|
+
## Success criteria
|
|
56
|
+
|
|
57
|
+
- Mid-turn context sampling cost stays bounded (~1% duty cycle) as sessions grow; visible in `/jar perf`.
|
|
58
|
+
- Plan/goal sessions keep prefix-cache hits across turns and rounds on every provider.
|
|
59
|
+
- Stored session history is unchanged.
|
package/docs/WORKFLOWS.md
CHANGED
|
@@ -68,7 +68,7 @@ State (`pi-jar.plan` entries, v2: `enabled`, `steps`, `text`, `path`, `title`) f
|
|
|
68
68
|
- **Task gate:** with no open task, `write`/`edit` are blocked, and so are shell commands that are not on the read-only allowlist during the implement phase. During the audit, edits are blocked but verification commands are allowed.
|
|
69
69
|
- **Roles per round:** implement rounds run on the `implement` role and the audit round on `advisor` (each only if assigned). The previous model and effort are restored when the run settles.
|
|
70
70
|
- **Completion:** `jar_goal complete` requires the audit phase, no open tasks, and non-empty evidence. It ends the turn, records the evidence, and Ember shows `(★ᴗ★)`.
|
|
71
|
-
- **Context hygiene:**
|
|
71
|
+
- **Context hygiene:** repeated identical goal context is sent once, and goal prompts already sent are never removed from the middle of the prompt while the goal runs, so any provider's prefix cache (Anthropic, OpenAI, Gemini, Bedrock, …) keeps hitting. A completed goal drops them all.
|
|
72
72
|
|
|
73
73
|
Goal events (`pi-jar.goal`, v2: `set`, `status`, `round`) are append-only session entries; v1 `set`/`clear` still replay.
|
|
74
74
|
|
package/extensions/index.ts
CHANGED
|
@@ -231,7 +231,7 @@ export default function piJar(pi: ExtensionAPI): void {
|
|
|
231
231
|
let subagentSignature = "";
|
|
232
232
|
subagents.subscribe(() => {
|
|
233
233
|
if (!footerTui) return;
|
|
234
|
-
const signature = subagents.
|
|
234
|
+
const signature = subagents.stateSignature();
|
|
235
235
|
repaint("subagents", signature === subagentSignature ? "background" : "transition");
|
|
236
236
|
subagentSignature = signature;
|
|
237
237
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-jar",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "A warm, role-aware Pi terminal workspace with switchable profiles, animated UI, plan and goal workflows, tasks, change review, model roles, background shells and subagents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/advisor.ts
CHANGED
|
@@ -239,7 +239,7 @@ export function registerAdvisor(pi: ExtensionAPI, roles: ModelRoleManager, optio
|
|
|
239
239
|
}
|
|
240
240
|
const selectedRoles = { resolve: () => primary, fallbackSpecs: () => fallbacks,
|
|
241
241
|
resolveSpec: (spec: string) => targets.get(spec)!() } as unknown as ModelRoleManager;
|
|
242
|
-
const selectedContext = { model: ctx.model, modelRegistry: ctx.modelRegistry } as ExtensionContext;
|
|
242
|
+
const selectedContext = { model: ctx.model, modelRegistry: ctx.modelRegistry, ui: ctx.ui } as ExtensionContext;
|
|
243
243
|
const conversation = transcript(sessionBranch(ctx) as readonly Entry[], 12_000);
|
|
244
244
|
const git = await gitState(ctx, controller.signal);
|
|
245
245
|
controller.signal.throwIfAborted();
|
package/src/delegate.ts
CHANGED
|
@@ -41,6 +41,9 @@ const allowedInMode = (mode: DelegateExecutionMode, name: string) => !RECURSIVE_
|
|
|
41
41
|
export type DelegateMode = "scout" | "fork" | "worktree";
|
|
42
42
|
type DelegateExecutionMode = DelegateMode | "direct";
|
|
43
43
|
const MAX_OUTPUT_CHARS = 12_000;
|
|
44
|
+
/** Shared budget for the reports one synchronous jar_delegate result returns; the rest stays one jar_subagent report away. */
|
|
45
|
+
const MAX_RESULT_REPORT_CHARS = 16_000;
|
|
46
|
+
const MIN_RUN_REPORT_CHARS = 2000;
|
|
44
47
|
/** A working child that sends no RPC event for this long is treated as hung and killed. */
|
|
45
48
|
const IDLE_TIMEOUT_MS = 10 * 60_000;
|
|
46
49
|
/** After exit, grandchildren (MCP servers, shells) can hold the stdio pipes open; stop waiting for close. */
|
|
@@ -1090,6 +1093,12 @@ export class DelegateRegistry {
|
|
|
1090
1093
|
for (const record of records) this.entries.set(record.key, { record });
|
|
1091
1094
|
this.notify();
|
|
1092
1095
|
}
|
|
1096
|
+
/** Key/state of every record in insertion order: a cheap change test for per-tick listeners (no sweep, sort or copies). */
|
|
1097
|
+
stateSignature(): string {
|
|
1098
|
+
let signature = "";
|
|
1099
|
+
for (const [key, { record }] of this.entries) signature += key + ":" + record.run.state + " ";
|
|
1100
|
+
return signature;
|
|
1101
|
+
}
|
|
1093
1102
|
notify(): void {
|
|
1094
1103
|
this.sweep();
|
|
1095
1104
|
for (const listener of this.listeners) {
|
|
@@ -1124,7 +1133,7 @@ const fileList = (files: readonly string[], limit: number) => files.slice(0, lim
|
|
|
1124
1133
|
const todoLine = (todo: Todo) => `${todo.parentId ? " " : " "}${todo.status === "completed" ? "[x]" : todo.status === "in_progress" ? "[~]" : "[ ]"} ${todo.title}`;
|
|
1125
1134
|
|
|
1126
1135
|
/** What the parent agent reads back: the run's facts (time, tools, files, tasks, failures), then its own report. */
|
|
1127
|
-
export function runReport(run: DelegateRun, now = Date.now()): string {
|
|
1136
|
+
export function runReport(run: DelegateRun, now = Date.now(), outputLimit = MAX_OUTPUT_CHARS, key?: string): string {
|
|
1128
1137
|
const counts = Object.entries(run.toolCounts).sort((a, b) => b[1] - a[1]).map(([name, count]) => `${name}×${count}`).join(", ");
|
|
1129
1138
|
const facts = [
|
|
1130
1139
|
run.startedAt !== undefined ? `took ${duration((run.endedAt ?? now) - run.startedAt)}` : "never started",
|
|
@@ -1143,7 +1152,10 @@ export function runReport(run: DelegateRun, now = Date.now()): string {
|
|
|
1143
1152
|
}
|
|
1144
1153
|
const failures = run.transcript.filter((entry): entry is ToolEntry => entry.kind === "tool" && entry.status === "error").slice(-5);
|
|
1145
1154
|
if (failures.length) lines.push(`- failed tool calls: ${failures.map((entry) => cleanText(`${entry.name} ${entry.hint}`, 80)).join("; ")}`);
|
|
1146
|
-
|
|
1155
|
+
const output = run.output.length > outputLimit
|
|
1156
|
+
? run.output.slice(0, outputLimit) + `\n… [report truncated; jar_subagent report ${key ?? run.name} returns the full text]`
|
|
1157
|
+
: run.output;
|
|
1158
|
+
lines.push("", output || "(no report)");
|
|
1147
1159
|
return lines.join("\n");
|
|
1148
1160
|
}
|
|
1149
1161
|
|
|
@@ -1809,7 +1821,9 @@ export function registerDelegate(pi: ExtensionAPI, roles: ModelRoleManager, regi
|
|
|
1809
1821
|
flushUpdate();
|
|
1810
1822
|
toolReturned = true;
|
|
1811
1823
|
}
|
|
1812
|
-
|
|
1824
|
+
const outputLimit = Math.max(MIN_RUN_REPORT_CHARS, Math.floor(MAX_RESULT_REPORT_CHARS / Math.max(1, runs.length)));
|
|
1825
|
+
const keys = new Map(records.map(({ key, run }) => [run, key]));
|
|
1826
|
+
return { content: [{ type: "text", text: runs.map((run) => runReport(run, Date.now(), outputLimit, keys.get(run))).join("\n\n") }], details: details(),
|
|
1813
1827
|
...(runs.some((run) => run.state === "failed") ? { isError: true } : {}) };
|
|
1814
1828
|
} finally { releaseReservation(); }
|
|
1815
1829
|
},
|
|
@@ -1917,7 +1931,7 @@ export function registerDelegate(pi: ExtensionAPI, roles: ModelRoleManager, regi
|
|
|
1917
1931
|
description: "Non-blocking moderator control for retained subagents. peek, steer, resume and discard return immediately. ask, pause and stop return an accepted operation receipt; the final answer or handoff arrives as a pi-jar.subagent event. Settled agents hibernate (process closed, context and workspace kept); resume and ask relaunch them transparently. Stop completion safely reconciles worktree changes; acceptance does not mean changes are applied yet. discard removes an unresolved worktree recovery workspace without applying it.",
|
|
1918
1932
|
promptSnippet: "Use jar_subagent as the moderator control plane. Prefer peek over rereading transcripts; reuse paused/idle/hibernated agents with resume; stop finished workers to reconcile their work.",
|
|
1919
1933
|
promptGuidelines: [
|
|
1920
|
-
"peek returns only task progress, plus workspace and changed files for unresolved worktree recovery records. Do not poll: initial/resumed turns and control completions send pi-jar.subagent events. Stop returns an accepted receipt first, then changed files and the full handoff in its completion event.",
|
|
1934
|
+
"peek returns only task progress, plus workspace and changed files for unresolved worktree recovery records. report returns an agent's latest full report when a result or event shows only part of it. Do not poll: initial/resumed turns and control completions send pi-jar.subagent events. Stop returns an accepted receipt first, then changed files and the full handoff in its completion event.",
|
|
1921
1935
|
"Use steer for active direction and ask for a brief BTW question. ask, pause and stop do not wait on the child; continue responding to the user until their completion event arrives.",
|
|
1922
1936
|
"Pause when an agent should stop spending tokens but keep its context/workspace. Resume the same agent later instead of spawning a replacement; a hibernated agent resumes exactly like an idle one.",
|
|
1923
1937
|
"Stop when an agent is no longer needed. Stop aborts any active turn, retires the process, reports progress/workspace/changes/remaining work, and reconciles safe worktree changes into /diff. On a failed/conflicted worktree recovery record, stop retries reconciliation; discard it only when its changes are not wanted."
|
|
@@ -1925,7 +1939,7 @@ export function registerDelegate(pi: ExtensionAPI, roles: ModelRoleManager, regi
|
|
|
1925
1939
|
parameters: Type.Object({
|
|
1926
1940
|
action: Type.Union([
|
|
1927
1941
|
Type.Literal("peek"), Type.Literal("steer"), Type.Literal("ask"),
|
|
1928
|
-
Type.Literal("pause"), Type.Literal("resume"), Type.Literal("stop"), Type.Literal("discard")
|
|
1942
|
+
Type.Literal("pause"), Type.Literal("resume"), Type.Literal("stop"), Type.Literal("discard"), Type.Literal("report")
|
|
1929
1943
|
]),
|
|
1930
1944
|
agent: Type.Optional(Type.String({ description: "Subagent key or unique name. Omit only for peek to show all retained agents." })),
|
|
1931
1945
|
message: Type.Optional(Type.String({ description: "Direction, BTW question, or resume instruction." }))
|
|
@@ -1942,6 +1956,7 @@ export function registerDelegate(pi: ExtensionAPI, roles: ModelRoleManager, regi
|
|
|
1942
1956
|
const agent = params.agent ?? "";
|
|
1943
1957
|
const record = registry.resolve(agent);
|
|
1944
1958
|
if (!record) return { content: [{ type: "text", text: "Subagent not found or name is ambiguous: " + agent }], isError: true };
|
|
1959
|
+
if (params.action === "report") return { content: [{ type: "text", text: runReport(record.run) }] };
|
|
1945
1960
|
const stopping = pendingControls.get(record.key + ":stop");
|
|
1946
1961
|
const controlling = pendingControls.get(record.key + ":control");
|
|
1947
1962
|
if (stopping || (controlling && params.action !== "stop")) {
|
package/src/goal-loop.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { Goal, GoalStore } from "./goals.ts";
|
|
|
5
5
|
import type { ModelRoleManager } from "./model-roles.ts";
|
|
6
6
|
import { isSafePlanCommand } from "./plan-utils.ts";
|
|
7
7
|
import type { Todo, TodoStore } from "./tasks.ts";
|
|
8
|
+
import { projectWorkflowMessages } from "./workflow-context.ts";
|
|
8
9
|
|
|
9
10
|
export const GOAL_TOOL = "jar_goal";
|
|
10
11
|
export const DEFAULT_GOAL_ROUNDS = 8;
|
|
@@ -267,31 +268,16 @@ export class GoalLoop {
|
|
|
267
268
|
return { message: { customType: CONTEXT_TYPE, content: this.context(goal), display: false } };
|
|
268
269
|
});
|
|
269
270
|
|
|
270
|
-
//
|
|
271
|
-
//
|
|
271
|
+
// Never drop an already-sent goal prompt mid-history while the goal runs: that would re-bill the
|
|
272
|
+
// previous run uncached. Repeated identical context is sent once; a finished goal drops all.
|
|
272
273
|
this.pi.on("context", async (event) => {
|
|
273
274
|
const goal = this.goal();
|
|
274
275
|
const active = !!goal && goal.status !== "complete";
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if (type === CONTEXT_TYPE) {
|
|
281
|
-
if (!active || latestContext >= 0) needsPrune = true;
|
|
282
|
-
else latestContext = index;
|
|
283
|
-
} else if (type === CONTINUATION_TYPE) {
|
|
284
|
-
if (!active || latestContinuation >= 0) needsPrune = true;
|
|
285
|
-
else latestContinuation = index;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
if (!needsPrune) return;
|
|
289
|
-
return { messages: event.messages.filter((raw, index) => {
|
|
290
|
-
const type = (raw as { customType?: string }).customType;
|
|
291
|
-
if (type === CONTEXT_TYPE) return active && index === latestContext;
|
|
292
|
-
if (type === CONTINUATION_TYPE) return active && index === latestContinuation;
|
|
293
|
-
return true;
|
|
294
|
-
}) };
|
|
276
|
+
const messages = projectWorkflowMessages(event.messages, {
|
|
277
|
+
[CONTEXT_TYPE]: { keep: active, dedupe: true },
|
|
278
|
+
[CONTINUATION_TYPE]: { keep: active }
|
|
279
|
+
});
|
|
280
|
+
if (messages) return { messages };
|
|
295
281
|
});
|
|
296
282
|
|
|
297
283
|
this.pi.on("agent_before_settle", async (event, ctx) => {
|
package/src/perf.ts
CHANGED
|
@@ -185,6 +185,9 @@ export class RenderScheduler {
|
|
|
185
185
|
|
|
186
186
|
/** Mid-turn context recomputation happens at most this often; boundaries refresh at once. */
|
|
187
187
|
export const CONTEXT_SAMPLE_MS = 750;
|
|
188
|
+
/** Costly samples widen the window to keep mid-turn sampling near a 1% duty cycle, up to this cap. */
|
|
189
|
+
export const CONTEXT_SAMPLE_MAX_MS = 5000;
|
|
190
|
+
const CONTEXT_SAMPLE_DUTY = 100;
|
|
188
191
|
export interface ContextUsageLike { percent?: number | null }
|
|
189
192
|
export interface ContextSamplingStats {
|
|
190
193
|
label: string;
|
|
@@ -197,6 +200,8 @@ export interface ContextSamplingStats {
|
|
|
197
200
|
/** Median over the latest samples. */
|
|
198
201
|
medianMs?: number;
|
|
199
202
|
lastSampleAgeMs?: number;
|
|
203
|
+
/** Current mid-turn throttle window, widened from the median sample cost. */
|
|
204
|
+
windowMs: number;
|
|
200
205
|
dirty: boolean;
|
|
201
206
|
pending: boolean;
|
|
202
207
|
}
|
|
@@ -253,20 +258,31 @@ export class ContextSampler {
|
|
|
253
258
|
const before = this.current;
|
|
254
259
|
this.sample();
|
|
255
260
|
if (this.current !== before) this.changed();
|
|
256
|
-
}, Math.max(0, (this.lastSampleAt ?? Number.NEGATIVE_INFINITY) + this.
|
|
261
|
+
}, Math.max(0, (this.lastSampleAt ?? Number.NEGATIVE_INFINITY) + this.windowMs() - this.now()));
|
|
257
262
|
this.timer.unref?.();
|
|
258
263
|
}
|
|
259
264
|
|
|
260
265
|
stats(): ContextSamplingStats {
|
|
261
|
-
const
|
|
266
|
+
const median = this.medianMs();
|
|
262
267
|
return {
|
|
263
268
|
label: this.current, ...this.counts,
|
|
264
|
-
...(
|
|
269
|
+
...(median !== undefined ? { medianMs: median } : {}),
|
|
265
270
|
...(this.lastSampleAt !== undefined ? { lastSampleAgeMs: this.now() - this.lastSampleAt } : {}),
|
|
266
|
-
dirty: this.stale, pending: this.timer !== undefined
|
|
271
|
+
windowMs: this.windowMs(), dirty: this.stale, pending: this.timer !== undefined
|
|
267
272
|
};
|
|
268
273
|
}
|
|
269
274
|
|
|
275
|
+
private medianMs(): number | undefined {
|
|
276
|
+
if (!this.durations.length) return undefined;
|
|
277
|
+
return [...this.durations].sort((a, b) => a - b)[Math.floor(this.durations.length / 2)]!;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Cost-adaptive: large sessions whose usage walk is slow sample less often mid-turn. */
|
|
281
|
+
private windowMs(): number {
|
|
282
|
+
const cost = (this.medianMs() ?? 0) * CONTEXT_SAMPLE_DUTY;
|
|
283
|
+
return Math.max(this.throttleMs, Math.min(CONTEXT_SAMPLE_MAX_MS, Math.round(cost)));
|
|
284
|
+
}
|
|
285
|
+
|
|
270
286
|
/** Session shutdown: no timer, and no reference to the old session's context. */
|
|
271
287
|
dispose(): void {
|
|
272
288
|
clearTimeout(this.timer);
|
|
@@ -386,6 +402,7 @@ export function formatPerf(snapshot: PerfSnapshot): string {
|
|
|
386
402
|
["dirty marks", count(sampling.marks)],
|
|
387
403
|
["total time", ms(sampling.totalMs)],
|
|
388
404
|
["max time", ms(sampling.maxMs) + (sampling.medianMs !== undefined ? ` (median ${ms(sampling.medianMs)})` : "")],
|
|
405
|
+
["window", ms(sampling.windowMs) + " mid-turn"],
|
|
389
406
|
["last sample age", sampling.lastSampleAgeMs !== undefined ? age(sampling.lastSampleAgeMs) : "never"],
|
|
390
407
|
["pending", sampling.pending ? "sample scheduled" : sampling.dirty ? "yes" : "no"]
|
|
391
408
|
]);
|
package/src/plan.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { extractApproachSteps, isSafePlanCommand, PLAN_TEMPLATE, planTextFromSte
|
|
|
11
11
|
import { cleanText } from "./status.ts";
|
|
12
12
|
import { sessionBranch } from "./session-branch.ts";
|
|
13
13
|
import { type TodoStore } from "./tasks.ts";
|
|
14
|
+
import { projectWorkflowMessages } from "./workflow-context.ts";
|
|
14
15
|
|
|
15
16
|
export const PLAN_ENTRY = "pi-jar.plan";
|
|
16
17
|
export const PLAN_SUBMIT_TOOL = "jar_plan_submit";
|
|
@@ -417,30 +418,14 @@ export class PlanMode {
|
|
|
417
418
|
return { message: { customType: "pi-jar.plan-context", content: this.context(), display: false } };
|
|
418
419
|
});
|
|
419
420
|
|
|
420
|
-
//
|
|
421
|
-
//
|
|
422
|
-
// rewrites apply to a single LLM call, so this runs on every call.
|
|
421
|
+
// Plan context is identical every turn: send its first copy only, keeping the cached prefix
|
|
422
|
+
// stable. Reminders stay in place while active; leaving plan mode drops all of them.
|
|
423
423
|
this.pi.on("context", async (event) => {
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
if (type === "pi-jar.plan-context") {
|
|
430
|
-
if (!this.enabled || latestContext >= 0) needsPrune = true;
|
|
431
|
-
else latestContext = index;
|
|
432
|
-
} else if (type === "pi-jar.plan-reminder") {
|
|
433
|
-
if (!this.enabled || latestReminder >= 0) needsPrune = true;
|
|
434
|
-
else latestReminder = index;
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
if (!needsPrune) return;
|
|
438
|
-
return { messages: event.messages.filter((raw, index) => {
|
|
439
|
-
const type = (raw as { customType?: string }).customType;
|
|
440
|
-
if (type === "pi-jar.plan-context") return this.enabled && index === latestContext;
|
|
441
|
-
if (type === "pi-jar.plan-reminder") return this.enabled && index === latestReminder;
|
|
442
|
-
return true;
|
|
443
|
-
}) };
|
|
424
|
+
const messages = projectWorkflowMessages(event.messages, {
|
|
425
|
+
"pi-jar.plan-context": { keep: this.enabled, dedupe: true },
|
|
426
|
+
"pi-jar.plan-reminder": { keep: this.enabled }
|
|
427
|
+
});
|
|
428
|
+
if (messages) return { messages };
|
|
444
429
|
});
|
|
445
430
|
|
|
446
431
|
this.pi.on("input", (event) => {
|
package/src/profiles.ts
CHANGED
|
@@ -16,7 +16,8 @@ export function conversationStarted(entries: readonly unknown[]): boolean {
|
|
|
16
16
|
|| (entry.type === "message" && isPlainObject(entry.message) && entry.message.role === "user")));
|
|
17
17
|
}
|
|
18
18
|
export function pinnedProfileId(entries: readonly unknown[]): string | undefined {
|
|
19
|
-
for (
|
|
19
|
+
for (let index = entries.length - 1; index >= 0; index--) {
|
|
20
|
+
const entry = entries[index];
|
|
20
21
|
if (isPlainObject(entry) && entry.type === "custom" && entry.customType === PROFILE_ENTRY
|
|
21
22
|
&& isPlainObject(entry.data) && entry.data.version === 1 && typeof entry.data.id === "string") return entry.data.id;
|
|
22
23
|
}
|
package/src/side-model.ts
CHANGED
|
@@ -26,6 +26,19 @@ export class SideUsage {
|
|
|
26
26
|
|
|
27
27
|
export interface SideAnswer { text: string; model: string }
|
|
28
28
|
|
|
29
|
+
/** Roles already told, this process, that they ran on the current (main) model. */
|
|
30
|
+
const unsetRoleNotices = new Set<string>();
|
|
31
|
+
|
|
32
|
+
/** An unassigned side role silently costs main-model prices; say so once per role. */
|
|
33
|
+
function noteCurrentModel(ctx: ExtensionContext, role: string, model: string): void {
|
|
34
|
+
if (unsetRoleNotices.has(role)) return;
|
|
35
|
+
unsetRoleNotices.add(role);
|
|
36
|
+
try {
|
|
37
|
+
ctx.ui?.notify(`${role} role is unset, so it used the current model (${model}). `
|
|
38
|
+
+ `Assign a cheaper one with /roles set ${role} PROVIDER/MODEL.`, "info");
|
|
39
|
+
} catch { /* the notice is advisory */ }
|
|
40
|
+
}
|
|
41
|
+
|
|
29
42
|
/**
|
|
30
43
|
* Ask the model assigned to `role` (or the current model) a one-shot question outside the
|
|
31
44
|
* conversation. Tries configured fallbacks in order on failure; cancellation never retries.
|
|
@@ -71,6 +84,7 @@ export async function askRole(ctx: ExtensionContext, roles: ModelRoleManager, us
|
|
|
71
84
|
}
|
|
72
85
|
text = text.trim();
|
|
73
86
|
if (!text) throw new Error(`${name} returned an empty answer`);
|
|
87
|
+
if (!assigned) noteCurrentModel(ctx, role, name);
|
|
74
88
|
return { text, model: name };
|
|
75
89
|
} catch (error) {
|
|
76
90
|
signal?.throwIfAborted();
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** How one hidden workflow message type is projected into provider context. */
|
|
2
|
+
export interface WorkflowMessageRule {
|
|
3
|
+
/** False drops every message of this type (its mode is off). */
|
|
4
|
+
keep: boolean;
|
|
5
|
+
/** Drop a message whose content repeats the previously kept one of the same type. */
|
|
6
|
+
dedupe?: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Provider-context projection for hidden workflow prompts (plan/goal context, reminders,
|
|
11
|
+
* continuations). Pi caches the conversation prefix, so a message once sent must keep being sent:
|
|
12
|
+
* every keep/drop decision depends only on the messages before it, never on later ones. Dropping
|
|
13
|
+
* an older copy when a newer one arrives would change the prefix and re-bill the whole previous
|
|
14
|
+
* run uncached. Returns undefined when nothing changes.
|
|
15
|
+
*/
|
|
16
|
+
export function projectWorkflowMessages<T>(messages: T[], rules: Readonly<Record<string, WorkflowMessageRule>>): T[] | undefined {
|
|
17
|
+
const last = new Map<string, string>();
|
|
18
|
+
let projected: T[] | undefined;
|
|
19
|
+
for (let index = 0; index < messages.length; index++) {
|
|
20
|
+
const message = messages[index]!;
|
|
21
|
+
const type = (message as { customType?: string }).customType;
|
|
22
|
+
const rule = type === undefined ? undefined : rules[type];
|
|
23
|
+
let keep = true;
|
|
24
|
+
if (rule) {
|
|
25
|
+
if (!rule.keep) keep = false;
|
|
26
|
+
else if (rule.dedupe) {
|
|
27
|
+
const raw = (message as { content?: unknown }).content;
|
|
28
|
+
const content = typeof raw === "string" ? raw : JSON.stringify(raw ?? "");
|
|
29
|
+
if (last.get(type!) === content) keep = false;
|
|
30
|
+
else last.set(type!, content);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!keep) projected ??= messages.slice(0, index);
|
|
34
|
+
else projected?.push(message);
|
|
35
|
+
}
|
|
36
|
+
return projected;
|
|
37
|
+
}
|