pi-code 1.0.11 → 1.0.12
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 +14 -8
- package/extensions/internal/project-approval.ts +36 -3
- package/extensions/mcp.ts +3 -1
- package/extensions/memory.ts +12 -4
- package/extensions/session-title.ts +17 -2
- package/extensions/status-line.ts +3 -1
- package/extensions/thinking.ts +10 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,30 +38,36 @@ One `pi install` and everything below loads on the next start. `pi list` shows w
|
|
|
38
38
|
| Feature | Reads / provides | Extension |
|
|
39
39
|
|---|---|---|
|
|
40
40
|
| Global + project rules | `~/.claude/rules`, `.claude/rules` (nearest at or above cwd); unscoped rules inlined in full, `paths:`-scoped rules surfaced as pointers and auto-attached (the rule body is appended to a read/edit/write result when a matching file is touched, once per rule per session) | `claude-rules.ts` |
|
|
41
|
-
| Custom slash commands | `.claude/commands/**/*.md` (namespaced `/dir:name`); `$ARGUMENTS` (with the `ARGUMENTS:` append when unused), 0-based `$ARGUMENTS[N]`/`$N`, named `arguments:` frontmatter, `${CLAUDE_SESSION_ID}`/`${CLAUDE_EFFORT}`/`${CLAUDE_SKILL_DIR}`/`${CLAUDE_PROJECT_DIR}` (in bodies and `allowed-tools` rules); `` !`cmd` `` and multi-line ```` ```! ```` bash (whitespace-bounded, merged stderr, 2-minute budget, a failure aborts the invocation with the documented exit-1 carveout), `@file` inlining; `allowed-tools` with `Bash(...)` and `Read`/`Edit`/`Write` path scopes enforced at call time (gitignore anchors, Edit governs writes), `disallowed-tools`, `argument-hint`, `model` (switches the session model for the command's turn, restored after), `shell: powershell` (
|
|
41
|
+
| Custom slash commands | `.claude/commands/**/*.md` (namespaced `/dir:name`); `$ARGUMENTS` (with the `ARGUMENTS:` append when unused), 0-based `$ARGUMENTS[N]`/`$N`, named `arguments:` frontmatter, `${CLAUDE_SESSION_ID}`/`${CLAUDE_EFFORT}`/`${CLAUDE_SKILL_DIR}`/`${CLAUDE_PROJECT_DIR}` (in bodies and `allowed-tools` rules); `` !`cmd` `` and multi-line ```` ```! ```` bash (whitespace-bounded, merged stderr, 2-minute budget, a failure aborts the invocation with the documented exit-1 carveout), `@file` inlining; `allowed-tools` with `Bash(...)` and `Read`/`Edit`/`Write` path scopes enforced at call time (gitignore anchors, Edit governs writes), `disallowed-tools`, `argument-hint`, `model` (switches the session model for the command's turn, restored after), `effort` (raises reasoning for the turn, restored after), `shell: powershell` (injected spans run through PowerShell when a `pwsh` binary is present, else `/bin/sh`); the model can also run a command itself through the `SlashCommand` tool (Claude's `SlashCommand` in `allowed-tools`), steered by `when_to_use` and opted out per file with `disable-model-invocation` (`user-invocable: false` hides a command from the menu while still exposing it to the model); `disableSkillShellExecution` (managed and user always, project when trusted) replaces every `!` span with a policy-disabled placeholder; project commands gated on approval | `commands.ts` |
|
|
42
42
|
| `/init` | generates a project context file: detects an existing `AGENTS.md`/`CLAUDE.md` (proposes improvements) or none (creates `AGENTS.md`, pi's preferred name), ingesting `.cursor/rules`, `.cursorrules`, and `.github/copilot-instructions.md` when present; drives the main agent with full tools via a prompt (not a tool-less completion) so it analyzes the codebase and writes the file itself | `init.ts` |
|
|
43
43
|
| Skills | `.claude/skills` → pi skill discovery, project skills gated on approval (pi reads `name`, `description`, `disable-model-invocation`; `allowed-tools` is inert in pi's loader) | `skills.ts` |
|
|
44
|
-
| Hooks | `.claude/settings.json` hooks: PreToolUse (blocks, rewrites input via `updatedInput`), PostToolUse (feedback and `additionalContext` land next to the tool result), PostToolUseFailure, SessionStart (context injection), UserPromptSubmit (blocks and injects context), Stop (a block continues the conversation), SubagentStart/SubagentStop, PreCompact, PostCompact, SessionEnd, Notification (idle_prompt, the type pi can source), InstructionsLoaded (observational: fires per loaded context file at session start, plus `path_glob_match` on a scoped-rule attach and `include` per resolved `@import`; deduped per session; `nested_traversal`/`compact` reasons never fire since pi does not lazily load nested CLAUDE.md or reload after compaction); `type: http` entries POST the payload (a 2xx JSON body renders the decision, everything else is non-blocking per Claude's contract), `type: prompt` evaluates in-process against the session model, `type: mcp_tool` calls a connected server's tool, and `type: agent` (experimental) spawns a read-only Read/Grep/Glob subagent that returns the JSON decision (a missing model/server/runner is non-blocking, only a PreToolUse timeout fails closed); Claude matcher semantics incl. `mcp__server__tool` names; payloads carry session_id, transcript_path, cwd, permission_mode, effort; `permissionDecision: "ask"` prompts via a confirm dialog (blocks when headless), SubagentStop/PostToolUseFailure are notify-only, and a timed-out PreToolUse/UserPromptSubmit hook fails closed at a 60s default (Claude: 600s, non-blocking) since pi has no permission backstop | `hooks.ts` |
|
|
44
|
+
| Hooks | `.claude/settings.json` hooks: PreToolUse (blocks, rewrites input via `updatedInput`), PostToolUse (feedback and `additionalContext` land next to the tool result), PostToolUseFailure, SessionStart (context injection), UserPromptSubmit (blocks and injects context), Stop (a block continues the conversation), SubagentStart/SubagentStop, PreCompact, PostCompact, SessionEnd, Notification (idle_prompt, the type pi can source), InstructionsLoaded (observational: fires per loaded context file at session start, plus `path_glob_match` on a scoped-rule attach and `include` per resolved `@import`; deduped per session; `nested_traversal`/`compact` reasons never fire since pi does not lazily load nested CLAUDE.md or reload after compaction); `type: http` entries POST the payload (a 2xx JSON body renders the decision, everything else is non-blocking per Claude's contract), `type: prompt` evaluates in-process against the session model, `type: mcp_tool` calls a connected server's tool, and `type: agent` (experimental) spawns a read-only Read/Grep/Glob subagent that returns the JSON decision (a missing model/server/runner is non-blocking, only a PreToolUse timeout fails closed); Claude matcher semantics incl. `mcp__server__tool` names; payloads carry session_id, transcript_path, cwd, permission_mode, effort; `permissionDecision: "ask"` prompts via a confirm dialog (blocks when headless), SubagentStop/PostToolUseFailure are notify-only, and a timed-out PreToolUse/UserPromptSubmit hook fails closed at a 60s default (Claude: 600s, non-blocking) since pi has no permission backstop; a `command` hook may use exec form (`command` as an argv array, run with no shell) and executes with `CLAUDECODE=1` and `CLAUDE_PROJECT_DIR` set; a user-typed `!`/`!!` bash line runs PreToolUse (there is no PostToolUse for it); `type: http` targets are gated by `allowedHttpHookUrls` (union of managed and settings scopes; unset allows all, `[]` blocks every http hook); a Stop hook may block at most 8 times before the turn ends (`CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`); `disableAllHooks` in any scope turns the system off; `/hooks` prints the resolved configuration | `hooks.ts` |
|
|
45
45
|
| Output styles | `.claude/output-styles` + active `outputStyle`; plus styles shipped by enabled plugins (manifest `outputStyles`, default `output-styles/`, ranked below the user's and project's own); Claude replace semantics with `keep-coding-instructions`; bundled Explanatory/Learning/Proactive; `/output-style [name]` | `output-styles.ts` |
|
|
46
|
-
| CLAUDE.md `@imports` and rewriting | resolves `@path` imports pi's native loader skips (4-hop depth, budget-capped); loads every `CLAUDE.local.md` from the repo root down to cwd (approval-gated, root first); injects managed `claudeMd` from `managed-settings.json` at the top of context; honors `claudeMdExcludes` (glob/absolute-path skip list from user, approved-project, and managed settings, merged; managed content never excluded); strips block-level HTML comments from CLAUDE.md, rule, and imported bodies (fenced-code comments preserved), so a commented-out `@import` does not expand; with `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` set, loads `CLAUDE.md`/`.claude/CLAUDE.md`/`.claude/rules/*.md`/`CLAUDE.local.md` from each `--add-dir` directory (comma-separated for several, since pi's flag is single-value) | `context-imports.ts` |
|
|
47
|
-
|
|
|
46
|
+
| CLAUDE.md `@imports` and rewriting | resolves `@path` imports pi's native loader skips (4-hop depth, budget-capped); loads the user `~/.claude/CLAUDE.md` and the project `.claude/CLAUDE.md` (approval-gated, deduped against the repo-root `CLAUDE.md`/`AGENTS.md` pi loads natively) that pi's own loader does not; loads every `CLAUDE.local.md` from the repo root down to cwd (approval-gated, root first); injects the managed `CLAUDE.md` (a per-OS file beside `managed-settings.json`) and the `claudeMd` string from `managed-settings.json` at the top of context (managed content is never excludable); honors `claudeMdExcludes` (glob/absolute-path skip list from user, approved-project, and managed settings, merged; managed content never excluded); strips block-level HTML comments from CLAUDE.md, rule, and imported bodies (fenced-code comments preserved), so a commented-out `@import` does not expand; with `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` set, loads `CLAUDE.md`/`.claude/CLAUDE.md`/`.claude/rules/*.md`/`CLAUDE.local.md` from each `--add-dir` directory (comma-separated for several, since pi's flag is single-value) | `context-imports.ts` |
|
|
47
|
+
| Settings `env` | `env` blocks from `managed-settings.json`, `~/.claude/settings.json`, and the project `.claude/settings.json`/`settings.local.json` exported into the session (per-key `managed > user > project`); the project scope is approval-gated (a repo's env can redirect providers), a shell `export` outranks user and project but a managed key overrides even that, and a key an approved project set is unset once a later session no longer defines it | `env-settings.ts` |
|
|
48
|
+
| MCP servers | user `~/.claude.json` (incl. per-project `projects[cwd]` local scope), `~/.pi/agent/mcp.json`; project `.mcp.json`, `.pi/mcp.json` (once approved; `enabledMcpjsonServers`/`disabledMcpjsonServers`/`enableAllProjectMcpServers` honored, consent keys only from non-repo settings); stdio/HTTP/SSE/WebSocket by `type` (WebSocket is url-only: any `headers`/`bearerToken`/`headersHelper` on a ws server is ignored with a warning); `${VAR:-default}` expansion; a `headersHelper` command whose stdout JSON merges into the transport headers (http/sse); a `managed-mcp.json` beside `managed-settings.json` takes exclusive control (only its servers load, every other scope and the approval flow suppressed; an empty file disables MCP); managed `allowedMcpServers`/`deniedMcpServers` read from `managed-settings.json` only (`{serverName}` entries, applied globally across scopes, allow list exclusive with an empty array = lockdown, deny wins); connect and per-call budgets (`MCP_TIMEOUT`/`MCP_TOOL_TIMEOUT`) over a 4-hour wall default, plus a 5-minute idle timeout that a progress notification resets (`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`, `0` disables); a connected server's prompts register as `/mcp__server__prompt` commands and its resources are reachable through the `list_mcp_resources`/`read_mcp_resource` tools; tools refresh on `list_changed`; bearer tokens, or OAuth for remote servers (browser login on 401 after a confirm, CSRF-guarded loopback callback, tokens under `~/.pi/agent/mcp-oauth`, silent refresh later) | `mcp.ts` |
|
|
48
49
|
| Project trust | prompts before loading project config (MCP servers, hooks, agents, rules, output styles, commands, skills) that pi would otherwise trust silently | `internal/project-approval.ts` |
|
|
49
|
-
| Subagents / Task | builtin Explore/Plan/general-purpose agents, `~/.claude/agents` and `~/.pi/agent/agents`, plus project `.claude/agents` and `.pi/agents` (scanned recursively into subfolders) merged by default once the project is trusted (project wins on a name clash); frontmatter `tools`/`disallowedTools`/`model` (sonnet/opus/haiku/fable tier aliases or a concrete id)/`effort`/`skills` preload/`permissionMode: plan`/`maxTurns`/`memory` (`user`/`project`/`local` give the child its own persistent store under `.claude/agent-memory[-local]`, injected with Read/Write/Edit enabled, gated on auto memory; the parent conversation's memory is never loaded into a subagent, matching Claude); parallel and chain modes (pi extensions), one nesting level; background runs with cancel and resume | `subagent/` |
|
|
50
|
+
| Subagents / Task | builtin Explore/Plan/general-purpose agents, `~/.claude/agents` and `~/.pi/agent/agents`, plus project `.claude/agents` and `.pi/agents` (scanned recursively into subfolders) merged by default once the project is trusted (project wins on a name clash); frontmatter `tools`/`disallowedTools`/`model` (sonnet/opus/haiku/fable tier aliases or a concrete id)/`effort`/`skills` preload/`permissionMode: plan`/`maxTurns`/`memory` (`user`/`project`/`local` give the child its own persistent store under `.claude/agent-memory[-local]`, injected with Read/Write/Edit enabled, gated on auto memory; the parent conversation's memory is never loaded into a subagent, matching Claude); parallel and chain modes (pi extensions), one nesting level; background runs with cancel and resume (`/tasks` lists them, `/agents` lists the discovered roster) | `subagent/` |
|
|
50
51
|
| Plan mode | `plan_mode_complete` tool, tool snapshot/restore that survives `/reload` | `plan-mode/` |
|
|
51
52
|
| Todo list | persistent overlay, status machine, compaction-safe | `todo.ts` |
|
|
52
53
|
| Checkpoints / rewind | shadow-repo snapshots; restore overwrites checkpointed files, keeps files created later; 100 per session, repos pruned after 30 days | `git-checkpoint.ts` |
|
|
53
54
|
| Persistent memory | per-repo memories under `~/.pi/agent/memory` keyed on the repository root (subdirectory sessions share one store, as Claude does; pi's own store, separate from Claude's), index injected each session within Claude's 200-line/25KB bound (YAML frontmatter and block HTML comments stripped before it counts or loads); a save that would overflow it reports why; a memory written with frontmatter gets a `modified:` ISO timestamp; honors `autoMemoryEnabled` (settings) and `CLAUDE_CODE_DISABLE_AUTO_MEMORY` (env) to turn it off, and `autoMemoryDirectory` (absolute or `~/`) to relocate the store | `memory.ts` |
|
|
54
55
|
| WebSearch / WebFetch | key-free DuckDuckGo search (with `allowed_domains`/`blocked_domains`); SSRF-guarded fetch that prefers markdown via `Accept` then converts HTML, with Claude's 15-minute per-URL cache and an optional `prompt` that runs the page through the model in-process and returns the answer (falls back to markdown when headless or on error) | `web.ts` |
|
|
55
56
|
| AskUserQuestion | 1-4 questions per call (asked in sequence), each with `header` and 2-4 options, single- or `multiSelect`, plus free-text | `question.ts` |
|
|
56
|
-
| Statusline | Claude `statusLine` command contract (stdin JSON incl. `version`, `hook_event_name`, `session_name`, cost durations and
|
|
57
|
+
| Statusline | Claude `statusLine` command contract (stdin JSON incl. `version`, `hook_event_name`, `session_name`, a `cost` block with wall and API durations and lines added/removed, a `context_window` token breakdown, `exceeds_200k_tokens`, and `rate_limits` carrying the `five_hour`/`seven_day` utilization and reset from the provider's rate-limit headers; `padding`, `refreshInterval`, 300ms debounce); built-in turn state + session cost fallback | `status-line.ts` |
|
|
57
58
|
| Notifications | terminal notification when a turn ends (OSC 777 / Kitty OSC 99 / Windows toast); honors `preferredNotifChannel` (`terminal_bell`, `notifications_disabled`, `iterm2_with_bell`, else desktop) from user settings; fires only when you "appear to be away" (approximated by turn duration, since pi exposes no terminal-focus signal) | `notify.ts` |
|
|
59
|
+
| Think keywords | raises reasoning for one turn when the prompt carries a keyword: `ultrathink` to the max, `think hard`/`think harder` to high, a bare `think` to medium; only ever raises, matched on word boundaries, and the prior level is restored once the turn settles | `thinking.ts` |
|
|
60
|
+
| Session title | names a new session from its first message with a single model call (shown in the session selector and the terminal title); never overwrites an existing name, best-effort, at most once per session | `session-title.ts` |
|
|
61
|
+
| `/context` | reports how much of the model's context window the session occupies (used, window, free, and percent), and reads pi's live usage so it reflects a compaction | `context-usage.ts` |
|
|
58
62
|
| Claude plugins | installed marketplace plugins (`~/.claude/plugins/cache`), active per `enabledPlugins` in user settings only (a checked-out repo cannot flip which code-bearing plugins run, so project settings never toggle them): commands as `/plugin:name`, agents, hooks and MCP servers (tools aliased `mcp__plugin_<plugin>_<server>__<tool>`) and output styles with `${CLAUDE_PLUGIN_ROOT}`/`${CLAUDE_PLUGIN_DATA}` and `${user_config.KEY}` (from `pluginConfigs[id].options` in user settings) substituted; skill dirs contribute too, though pi's loader names them without the plugin prefix | `internal/plugins.ts` |
|
|
59
63
|
|
|
64
|
+
Slash commands: `/init`, `/context`, `/memory`, `/todos`, `/rewind`, `/tasks`, `/agents`, `/plan`, `/mcp`, `/hooks`, and `/output-style`, alongside your own `/dir:name` commands, `/skill:name` skills, `/plugin:name` plugin commands, and each connected server's `/mcp__server__prompt` prompts.
|
|
65
|
+
|
|
60
66
|
pi has no general permission system, so most of what Claude routes through a permission prompt maps to hard behavior here: `allowed-tools` restricts the turn's tool set instead of pre-approving calls, and a hook that times out on PreToolUse or UserPromptSubmit fails closed. A hook's `permissionDecision: "ask"` is the exception: it shows a confirm dialog and lets the call through when you approve (a headless run has no dialog, so it blocks). Where a Claude restriction cannot be expressed at all (an argument-scoped grant in an agent's `tools:`), the definition is rejected rather than widened.
|
|
61
67
|
|
|
62
|
-
`CLAUDE.md` itself needs no extension: pi loads `CLAUDE.md` / `AGENTS.md` context files natively (global + walking cwd to root). `context-imports.ts` only adds the `@import` resolution pi's loader lacks, appending the imported files without re-injecting the base.
|
|
68
|
+
`CLAUDE.md` itself needs no extension: pi loads `CLAUDE.md` / `AGENTS.md` context files natively (global + walking cwd to root). `context-imports.ts` only adds the `@import` resolution pi's loader lacks, appending the imported files without re-injecting the base. Setting `CLAUDE_CONFIG_DIR` relocates the entire home config scope (settings, commands, agents, skills, plugins, output styles, memory, and the user `CLAUDE.md`); a project's own `.claude/` is a separate scope and is unaffected.
|
|
63
69
|
|
|
64
|
-
`extensions/internal/` holds shared modules pi's loader must not treat as extensions: `output-guard.ts` (context-budget truncation), `web-transport.ts` (DNS-pinned fetch), `project-approval.ts` (the trust decision above), `command-file.ts` (slash-command parsing and dynamic content), and the shared-bus contracts `mcp-alias.ts`, `plan-mode-state.ts` and `subagent-events.ts`. The extensions use them; only `internal/` keeps them out of pi's extension scan.
|
|
70
|
+
`extensions/internal/` holds shared modules pi's loader must not treat as extensions: `output-guard.ts` (context-budget truncation), `web-transport.ts` (DNS-pinned fetch), `project-approval.ts` (the trust decision above), `command-file.ts` (slash-command parsing and dynamic content), `config-dir.ts` (the `CLAUDE_CONFIG_DIR` home-scope resolver), `managed-settings.ts` (the enterprise policy file), `model-complete.ts` (the in-process model calls behind session titling and prompt hooks), `mcp-oauth.ts` (the OAuth loopback), and the shared-bus contracts `mcp-alias.ts`, `plan-mode-state.ts` and `subagent-events.ts`. The extensions use them; only `internal/` keeps them out of pi's extension scan.
|
|
65
71
|
|
|
66
72
|
Vendored bases (`question`, `notify`, `status-line`) come from pi's MIT example extensions (see [LICENSE](LICENSE)).
|
|
67
73
|
|
|
@@ -61,7 +61,7 @@ export interface ApprovalContext {
|
|
|
61
61
|
cwd: string
|
|
62
62
|
hasUI: boolean
|
|
63
63
|
isProjectTrusted?: () => boolean
|
|
64
|
-
ui: { confirm: (title: string, body: string) => Promise<boolean
|
|
64
|
+
ui: { confirm: (title: string, body: string) => Promise<boolean>; notify?: (message: string, type?: 'info' | 'warning' | 'error') => void }
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
export interface ApprovalDeps {
|
|
@@ -80,6 +80,37 @@ const defaultDeps: ApprovalDeps = {
|
|
|
80
80
|
|
|
81
81
|
const APPROVAL_BODY = 'It ships Claude Code configuration that pi-code loads. MCP servers, hooks and agents can run commands from this repository.'
|
|
82
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Shown once when the pi runtime predates project-trust support. pi >= 0.79.1 hands
|
|
85
|
+
* extensions a `ctx.isProjectTrusted` callback; older runtimes omit it, and the trust
|
|
86
|
+
* guard below then reads every project as untrusted, so trust prompts, project hooks, MCP,
|
|
87
|
+
* commands, skills and rules all fail closed with nothing said. A live run on such a pi
|
|
88
|
+
* produced no error anywhere; this turns that silence into one line.
|
|
89
|
+
*/
|
|
90
|
+
const RUNTIME_TOO_OLD = 'pi-code requires pi >= 0.79.1 for project configuration; project-scoped .claude config stays disabled on this pi version'
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Whether the runtime lacks the `isProjectTrusted` capability, warning once when it does.
|
|
94
|
+
*
|
|
95
|
+
* The notice fires at most once per process and the guard is never reset: a pi binary
|
|
96
|
+
* cannot change version mid-run, so a single notice carries all the information a session
|
|
97
|
+
* can, and repeating it on every gated surface would be noise. Both the prompting and the
|
|
98
|
+
* silent callers report it. A missing runtime capability is not an approval question, so
|
|
99
|
+
* surfacing it from the silent variant is correct rather than a stray dialog. `ctx.ui` may
|
|
100
|
+
* be absent on a headless run, so the notify is fully optional-chained. Callers still fail
|
|
101
|
+
* closed on a true return, exactly as before.
|
|
102
|
+
*/
|
|
103
|
+
let warnedRuntimeTooOld = false
|
|
104
|
+
|
|
105
|
+
function runtimeLacksProjectTrust(ctx: { isProjectTrusted?: () => boolean; ui?: { notify?: (message: string, type?: 'info' | 'warning' | 'error') => void } }): boolean {
|
|
106
|
+
if (typeof ctx.isProjectTrusted === 'function') return false
|
|
107
|
+
if (!warnedRuntimeTooOld) {
|
|
108
|
+
warnedRuntimeTooOld = true
|
|
109
|
+
ctx.ui?.notify?.(RUNTIME_TOO_OLD, 'warning')
|
|
110
|
+
}
|
|
111
|
+
return true
|
|
112
|
+
}
|
|
113
|
+
|
|
83
114
|
/**
|
|
84
115
|
* Whether project-controlled config may be acted on.
|
|
85
116
|
*
|
|
@@ -90,7 +121,8 @@ const APPROVAL_BODY = 'It ships Claude Code configuration that pi-code loads. MC
|
|
|
90
121
|
/** The same decision as isProjectApproved, but never prompts: an undecided project
|
|
91
122
|
* reads as unapproved. For surfaces that only display project config, like the
|
|
92
123
|
* subagent roster, where a mid-turn dialog would be wrong. */
|
|
93
|
-
export function isProjectApprovedSilently(ctx: Pick<ApprovalContext, 'cwd' | 'isProjectTrusted'
|
|
124
|
+
export function isProjectApprovedSilently(ctx: Pick<ApprovalContext, 'cwd' | 'isProjectTrusted'> & { ui?: ApprovalContext['ui'] }, deps: ApprovalDeps = defaultDeps): boolean {
|
|
125
|
+
if (runtimeLacksProjectTrust(ctx)) return false // pi predates project-trust support
|
|
94
126
|
if (ctx.isProjectTrusted?.() !== true) return false
|
|
95
127
|
if (!deps.hasClaudeShaped(ctx.cwd)) return true
|
|
96
128
|
if (deps.piWouldAsk(ctx.cwd)) return true
|
|
@@ -98,7 +130,8 @@ export function isProjectApprovedSilently(ctx: Pick<ApprovalContext, 'cwd' | 'is
|
|
|
98
130
|
}
|
|
99
131
|
|
|
100
132
|
export async function isProjectApproved(ctx: ApprovalContext, deps: ApprovalDeps = defaultDeps): Promise<boolean> {
|
|
101
|
-
if (ctx
|
|
133
|
+
if (runtimeLacksProjectTrust(ctx)) return false // pi predates project-trust support
|
|
134
|
+
if (ctx.isProjectTrusted?.() !== true) return false // pi declined trust for this project
|
|
102
135
|
if (!deps.hasClaudeShaped(ctx.cwd)) return true // nothing here pi's own check would miss
|
|
103
136
|
if (deps.piWouldAsk(ctx.cwd)) return true // pi genuinely prompted for this project
|
|
104
137
|
|
package/extensions/mcp.ts
CHANGED
|
@@ -1243,7 +1243,9 @@ export default async function mcpExtension(pi: ExtensionAPI) {
|
|
|
1243
1243
|
for (const [name, client] of Array.from(clients.entries())) {
|
|
1244
1244
|
if (managedNames.has(name)) continue
|
|
1245
1245
|
clients.delete(name)
|
|
1246
|
-
|
|
1246
|
+
// Bound the close like session_shutdown does: a hung server must not stall the new
|
|
1247
|
+
// session start, which awaits this eviction before connecting the managed set.
|
|
1248
|
+
await withTimeout(client.close(), 3000, 'close').catch(() => {})
|
|
1247
1249
|
status.set(name, { state: 'disabled by managed policy', tools: 0 })
|
|
1248
1250
|
}
|
|
1249
1251
|
await connectServers(managedServers, authUi)
|
package/extensions/memory.ts
CHANGED
|
@@ -271,11 +271,17 @@ function readIndexQuietly(dir: string): string {
|
|
|
271
271
|
}
|
|
272
272
|
}
|
|
273
273
|
|
|
274
|
+
/** Write through a temp file and rename onto the target, so a crash mid-write cannot
|
|
275
|
+
* truncate it. The tmp name carries the pid so concurrent processes do not collide. */
|
|
276
|
+
function atomicWriteFile(filePath: string, content: string): void {
|
|
277
|
+
const tmp = `${filePath}.${process.pid}.tmp`
|
|
278
|
+
fs.writeFileSync(tmp, content)
|
|
279
|
+
fs.renameSync(tmp, filePath)
|
|
280
|
+
}
|
|
281
|
+
|
|
274
282
|
/** Replace the index through a rename so a crash mid-write cannot truncate it. */
|
|
275
283
|
function writeIndex(indexPath: string, content: string): void {
|
|
276
|
-
|
|
277
|
-
fs.writeFileSync(tmp, content)
|
|
278
|
-
fs.renameSync(tmp, indexPath)
|
|
284
|
+
atomicWriteFile(indexPath, content)
|
|
279
285
|
}
|
|
280
286
|
|
|
281
287
|
/** The settings chain that decides `autoMemoryEnabled` and `autoMemoryDirectory`:
|
|
@@ -337,7 +343,9 @@ export function setAutoMemoryEnabledSetting(home: string, value: boolean): { ok:
|
|
|
337
343
|
}
|
|
338
344
|
current.autoMemoryEnabled = value
|
|
339
345
|
fs.mkdirSync(dir, { recursive: true })
|
|
340
|
-
|
|
346
|
+
// Atomic like writeIndex: a crash mid-write must not truncate the user's settings, which
|
|
347
|
+
// also hold their hooks, env and permissions config.
|
|
348
|
+
atomicWriteFile(file, `${JSON.stringify(current, null, 2)}\n`)
|
|
341
349
|
return { ok: true }
|
|
342
350
|
}
|
|
343
351
|
|
|
@@ -92,9 +92,14 @@ export default function sessionTitleExtension(pi: ExtensionAPI) {
|
|
|
92
92
|
// One title per session, reset when a new session takes over so a resumed or forked
|
|
93
93
|
// session can still earn its own name.
|
|
94
94
|
let titled = false
|
|
95
|
+
// Bumped on every session_start. Captured before the model call so a title that resolves
|
|
96
|
+
// after a /new (which resets state to a different session) is recognized as stale and
|
|
97
|
+
// dropped, rather than renaming whoever holds the session slot now.
|
|
98
|
+
let generation = 0
|
|
95
99
|
|
|
96
100
|
pi.on('session_start', () => {
|
|
97
101
|
titled = false
|
|
102
|
+
generation++
|
|
98
103
|
})
|
|
99
104
|
|
|
100
105
|
pi.on('agent_settled', async (_event, ctx) => {
|
|
@@ -109,6 +114,7 @@ export default function sessionTitleExtension(pi: ExtensionAPI) {
|
|
|
109
114
|
// Claim the single attempt before the await, so overlapping or repeated settles cannot
|
|
110
115
|
// each fire a model call; a failed attempt below is not retried within this session.
|
|
111
116
|
titled = true
|
|
117
|
+
const startedGeneration = generation
|
|
112
118
|
let title: string
|
|
113
119
|
try {
|
|
114
120
|
const { text } = await completeText(model, `First user message of a new coding session:\n\n${prompt.slice(0, MAX_PROMPT_CHARS)}`, {
|
|
@@ -120,7 +126,16 @@ export default function sessionTitleExtension(pi: ExtensionAPI) {
|
|
|
120
126
|
return // no model, provider error: leave the session untitled (best-effort)
|
|
121
127
|
}
|
|
122
128
|
if (!title) return
|
|
123
|
-
|
|
124
|
-
|
|
129
|
+
// A /new during the await moved us to a different session, or a name has since been set;
|
|
130
|
+
// applying this title now would rename the wrong session, so drop it.
|
|
131
|
+
if (generation !== startedGeneration || pi.getSessionName?.()) return
|
|
132
|
+
// Post-await ctx getters throw once the session is disposed, and an escaping rejection
|
|
133
|
+
// from this un-awaited settle can exit pi; apply the title best-effort.
|
|
134
|
+
try {
|
|
135
|
+
pi.setSessionName(title)
|
|
136
|
+
ctx.ui.setTitle?.(title)
|
|
137
|
+
} catch {
|
|
138
|
+
// disposed session or a setter failure: leave the session untitled.
|
|
139
|
+
}
|
|
125
140
|
})
|
|
126
141
|
}
|
|
@@ -105,7 +105,9 @@ function readRateLimitWindow(headers: Record<string, string>, prefix: string): R
|
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
107
|
if (usedPercentage === undefined) return undefined
|
|
108
|
-
|
|
108
|
+
// A provider can report a utilization above 100 (or a remaining above the limit, making
|
|
109
|
+
// the computed value negative); clamp so the payload never carries a nonsense percentage.
|
|
110
|
+
const window: RateLimitWindow = { used_percentage: Math.max(0, Math.min(100, usedPercentage)) }
|
|
109
111
|
const resetsAt = headers[`${base}-reset`] ?? headers[`${base}-resets-at`]
|
|
110
112
|
if (resetsAt) window.resets_at = resetsAt
|
|
111
113
|
return window
|
package/extensions/thinking.ts
CHANGED
|
@@ -51,6 +51,16 @@ export default function thinkingExtension(pi: ExtensionAPI) {
|
|
|
51
51
|
// source 'extension' (a subagent prompt, a command body replayed through it); a
|
|
52
52
|
// think keyword the user did not type must not escalate, mirroring hooks.ts's guard.
|
|
53
53
|
if (event.source === 'extension') return
|
|
54
|
+
// A prompt that escalated but was then BLOCKED by a hook runs no turn, so no
|
|
55
|
+
// agent_settled ever fires to restore the level. The arrival of a new input is the
|
|
56
|
+
// signal that the prior prompt is gone: if this extension still owns the level (it is
|
|
57
|
+
// exactly our escalation target), restore before handling this input. In the normal
|
|
58
|
+
// path a settle already cleared pending, so this fires only for the blocked case.
|
|
59
|
+
if (pendingRestore !== undefined && (pi.getThinkingLevel?.() ?? ctx.thinkingLevel) === pendingTarget) {
|
|
60
|
+
pi.setThinkingLevel?.(pendingRestore)
|
|
61
|
+
pendingRestore = undefined
|
|
62
|
+
pendingTarget = undefined
|
|
63
|
+
}
|
|
54
64
|
const target = requestedThinkingLevel(event.text)
|
|
55
65
|
if (!target) return
|
|
56
66
|
const current = pi.getThinkingLevel?.() ?? ctx.thinkingLevel ?? 'off'
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-code",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"description": "Claude Code experience for the pi coding agent: reads your .claude config (rules, commands, skills, hooks, output styles, MCP servers, agents) and adds todo, checkpoints, memory, web, and subagents",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|