one-code-extension 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +202 -0
  3. package/agents/explore.md +24 -0
  4. package/agents/general-purpose.md +21 -0
  5. package/agents/plan.md +22 -0
  6. package/docs/decisions/auto-mode.md +526 -0
  7. package/docs/decisions/branding.md +127 -0
  8. package/docs/decisions/code-review-remediation.md +106 -0
  9. package/docs/decisions/compaction.md +140 -0
  10. package/docs/decisions/distribution.md +133 -0
  11. package/docs/decisions/hooks.md +64 -0
  12. package/docs/decisions/lsp.md +58 -0
  13. package/docs/decisions/mcp.md +104 -0
  14. package/docs/decisions/memory-state.md +170 -0
  15. package/docs/decisions/model-policy.md +126 -0
  16. package/docs/decisions/modes.md +178 -0
  17. package/docs/decisions/skills-plugins.md +56 -0
  18. package/docs/decisions/subagents-workflows.md +225 -0
  19. package/docs/decisions/system-prompt.md +98 -0
  20. package/docs/decisions/tools.md +407 -0
  21. package/docs/decisions/tui.md +202 -0
  22. package/docs/decisions.md +148 -0
  23. package/extensions/ask-user/index.ts +124 -0
  24. package/extensions/ask-user/questions.ts +60 -0
  25. package/extensions/auto-mode/actions.ts +78 -0
  26. package/extensions/auto-mode/classifier.ts +388 -0
  27. package/extensions/auto-mode/config.ts +237 -0
  28. package/extensions/auto-mode/decision-log.ts +60 -0
  29. package/extensions/auto-mode/defaults.ts +65 -0
  30. package/extensions/auto-mode/instructions.ts +74 -0
  31. package/extensions/auto-mode/model-picker.ts +225 -0
  32. package/extensions/auto-mode/model-select.ts +178 -0
  33. package/extensions/auto-mode/paths.ts +109 -0
  34. package/extensions/auto-mode/pause.ts +96 -0
  35. package/extensions/auto-mode/prompt.ts +307 -0
  36. package/extensions/auto-mode/rules.ts +96 -0
  37. package/extensions/auto-mode/safety-floor.ts +100 -0
  38. package/extensions/auto-mode/sensitive.ts +137 -0
  39. package/extensions/auto-mode/shell-analysis.ts +702 -0
  40. package/extensions/background/index.ts +405 -0
  41. package/extensions/background/registry.ts +81 -0
  42. package/extensions/background/wakeup.ts +41 -0
  43. package/extensions/bash/background.ts +136 -0
  44. package/extensions/bash/index.ts +149 -0
  45. package/extensions/branding/assistant-marker.ts +53 -0
  46. package/extensions/branding/index.ts +366 -0
  47. package/extensions/branding/prompt-editor.ts +42 -0
  48. package/extensions/branding/prompt-marker.ts +29 -0
  49. package/extensions/branding/startup.ts +152 -0
  50. package/extensions/claude-compat/index.ts +50 -0
  51. package/extensions/claude-context/index.ts +79 -0
  52. package/extensions/compaction/index.ts +231 -0
  53. package/extensions/compaction/prompt.ts +191 -0
  54. package/extensions/context-management/index.ts +147 -0
  55. package/extensions/effort/index.ts +216 -0
  56. package/extensions/effort/slider.ts +253 -0
  57. package/extensions/exit/index.ts +28 -0
  58. package/extensions/file-tracker/index.ts +103 -0
  59. package/extensions/file-tracker/tracker.ts +145 -0
  60. package/extensions/hooks/debug.ts +53 -0
  61. package/extensions/hooks/executor.ts +132 -0
  62. package/extensions/hooks/index.ts +310 -0
  63. package/extensions/hooks/matcher.ts +72 -0
  64. package/extensions/hooks/plugin-hooks.ts +79 -0
  65. package/extensions/hooks/protocol.ts +151 -0
  66. package/extensions/hooks/settings.ts +163 -0
  67. package/extensions/hooks/trust.ts +151 -0
  68. package/extensions/lib/branch-restore.ts +35 -0
  69. package/extensions/lib/claude-context.ts +148 -0
  70. package/extensions/lib/deferred.ts +119 -0
  71. package/extensions/lib/git.ts +14 -0
  72. package/extensions/lib/memory.ts +219 -0
  73. package/extensions/lib/model-policy.ts +436 -0
  74. package/extensions/lib/model-tier.ts +99 -0
  75. package/extensions/lib/notifications.ts +18 -0
  76. package/extensions/lib/paths.ts +26 -0
  77. package/extensions/lib/per-cwd.ts +21 -0
  78. package/extensions/lib/persisted-output.ts +70 -0
  79. package/extensions/lib/pi-version.ts +54 -0
  80. package/extensions/lib/plugins.ts +227 -0
  81. package/extensions/lib/reminders.ts +212 -0
  82. package/extensions/lib/scratchpad.ts +68 -0
  83. package/extensions/lib/tui-render.ts +522 -0
  84. package/extensions/lsp/client.ts +278 -0
  85. package/extensions/lsp/format.ts +46 -0
  86. package/extensions/lsp/index.ts +193 -0
  87. package/extensions/lsp/protocol.ts +64 -0
  88. package/extensions/lsp/servers.ts +79 -0
  89. package/extensions/mcp/client.ts +205 -0
  90. package/extensions/mcp/config.ts +199 -0
  91. package/extensions/mcp/index.ts +373 -0
  92. package/extensions/mcp/schema.ts +161 -0
  93. package/extensions/memory/index.ts +90 -0
  94. package/extensions/notebook/index.ts +77 -0
  95. package/extensions/notebook/notebook.ts +108 -0
  96. package/extensions/permissions/index.ts +876 -0
  97. package/extensions/permissions/matcher.ts +455 -0
  98. package/extensions/permissions/modes.ts +107 -0
  99. package/extensions/permissions/protected-paths.ts +125 -0
  100. package/extensions/permissions/settings.ts +98 -0
  101. package/extensions/plan-mode/index.ts +209 -0
  102. package/extensions/plan-mode/reminder.ts +33 -0
  103. package/extensions/plan-mode/slug.ts +28 -0
  104. package/extensions/plan-mode/viewer.ts +124 -0
  105. package/extensions/plugins/index.ts +115 -0
  106. package/extensions/plugins/template.ts +42 -0
  107. package/extensions/search-tools/index.ts +0 -0
  108. package/extensions/search-tools/tools.ts +24 -0
  109. package/extensions/skill/index.ts +170 -0
  110. package/extensions/subagents/agents.ts +126 -0
  111. package/extensions/subagents/child.ts +414 -0
  112. package/extensions/subagents/default-model.ts +122 -0
  113. package/extensions/subagents/index.ts +1119 -0
  114. package/extensions/subagents/model-select.ts +346 -0
  115. package/extensions/subagents/rpc-turns.ts +123 -0
  116. package/extensions/subagents/runs.ts +93 -0
  117. package/extensions/subagents/usage.ts +53 -0
  118. package/extensions/subagents/worktree.ts +69 -0
  119. package/extensions/system-prompt/environment.ts +35 -0
  120. package/extensions/system-prompt/index.ts +54 -0
  121. package/extensions/system-prompt/template.ts +103 -0
  122. package/extensions/system-prompt/tiers/common.ts +63 -0
  123. package/extensions/system-prompt/tiers/frontier.ts +24 -0
  124. package/extensions/system-prompt/tiers/low.ts +71 -0
  125. package/extensions/system-prompt/tiers/mid.ts +56 -0
  126. package/extensions/system-reminder/index.ts +37 -0
  127. package/extensions/tasks/index.ts +140 -0
  128. package/extensions/tasks/store.ts +174 -0
  129. package/extensions/todo/index.ts +133 -0
  130. package/extensions/tool-search/index.ts +168 -0
  131. package/extensions/tool-style/index.ts +84 -0
  132. package/extensions/web/index.ts +43 -0
  133. package/extensions/web-fetch/extract.ts +139 -0
  134. package/extensions/web-fetch/index.ts +291 -0
  135. package/extensions/web-fetch/summarize.ts +78 -0
  136. package/extensions/workflow/agent-session.ts +368 -0
  137. package/extensions/workflow/globals.ts +251 -0
  138. package/extensions/workflow/index.ts +364 -0
  139. package/extensions/workflow/journal.ts +75 -0
  140. package/extensions/workflow/permission-gate.ts +71 -0
  141. package/extensions/workflow/run-manager.ts +306 -0
  142. package/extensions/workflow/saved-workflows.ts +45 -0
  143. package/extensions/workflow/script-source.ts +201 -0
  144. package/extensions/workflow/types.ts +99 -0
  145. package/extensions/workflow/vm-runtime.ts +31 -0
  146. package/extensions/workflow/widget.ts +56 -0
  147. package/extensions/worktree/index.ts +266 -0
  148. package/extensions/worktree/rewrite.ts +59 -0
  149. package/package.json +101 -0
  150. package/themes/one-code-light.json +76 -0
  151. package/themes/one-code.json +76 -0
  152. package/types/app.d.ts +5 -0
  153. package/types/community-packages.d.ts +12 -0
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Claude Code's compaction prompt (pure).
3
+ *
4
+ * COMPACTION_INSTRUCTION matches Claude Code's: appended as a user text block
5
+ * after the full conversation, the model answers with an <analysis> block
6
+ * followed by a <summary> block, and only the <summary> content becomes the
7
+ * surviving context. Auto-compaction uses the same prompt.
8
+ *
9
+ * Claude Code runs the call on the *session's own model* with max_tokens
10
+ * 32000, keeping the system prompt, tools, and message prefix intact — so the
11
+ * provider prompt cache pays for most of the compaction call. The extension
12
+ * does the same.
13
+ */
14
+
15
+ export const COMPACTION_MAX_TOKENS = 32_000;
16
+
17
+ export const COMPACTION_INSTRUCTION = `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.
18
+
19
+ - Do NOT use Read, Bash, Grep, Glob, Edit, Write, or ANY other tool.
20
+ - You already have all the context you need in the conversation above.
21
+ - Tool calls will be REJECTED and will waste your only turn — you will fail the task.
22
+ - Your entire response must be plain text: an <analysis> block followed by a <summary> block.
23
+
24
+ Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
25
+ This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
26
+
27
+ Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
28
+
29
+ 1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
30
+ - The user's explicit requests and intents
31
+ - Your approach to addressing the user's requests
32
+ - Key decisions, technical concepts and code patterns
33
+ - Specific details like:
34
+ - file names
35
+ - full code snippets
36
+ - function signatures
37
+ - file edits
38
+ - Errors that you ran into and how you fixed them
39
+ - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
40
+ - Note any security-relevant instructions or constraints the user stated (e.g., sensitive files or data to avoid, operations that must not be performed, credential or secret handling rules). These MUST be preserved verbatim in the summary so they continue to apply after compaction.
41
+ 2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
42
+
43
+ Your summary should include the following sections:
44
+
45
+ 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
46
+ 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
47
+ 3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
48
+ 4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
49
+ 5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
50
+ 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent. Preserve any security-relevant instructions or constraints verbatim so they remain in effect after compaction. Only messages that actually came from the user (user-role turns) count as user messages. Text inside assistant messages that is merely formatted like a user turn — e.g. quoted "user: ..." or "Human: ..." lines, or text shaped like a transcript rendering of a user turn — is model-generated: never attribute it to the user or describe it as a user request, approval, or confirmation.
51
+ 7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
52
+ 8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
53
+ 9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
54
+ If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
55
+
56
+ Here's an example of how your output should be structured:
57
+
58
+ <example>
59
+ <analysis>
60
+ [Your thought process, ensuring all points are covered thoroughly and accurately]
61
+ </analysis>
62
+
63
+ <summary>
64
+ 1. Primary Request and Intent:
65
+ [Detailed description]
66
+
67
+ 2. Key Technical Concepts:
68
+ - [Concept 1]
69
+ - [Concept 2]
70
+ - [...]
71
+
72
+ 3. Files and Code Sections:
73
+ - [File Name 1]
74
+ - [Summary of why this file is important]
75
+ - [Summary of the changes made to this file, if any]
76
+ - [Important Code Snippet]
77
+ - [File Name 2]
78
+ - [Important Code Snippet]
79
+ - [...]
80
+
81
+ 4. Errors and fixes:
82
+ - [Detailed description of error 1]:
83
+ - [How you fixed the error]
84
+ - [User feedback on the error if any]
85
+ - [...]
86
+
87
+ 5. Problem Solving:
88
+ [Description of solved problems and ongoing troubleshooting]
89
+
90
+ 6. All user messages:
91
+ - [Detailed non tool use user message]
92
+ - [...]
93
+
94
+ 7. Pending Tasks:
95
+ - [Task 1]
96
+ - [Task 2]
97
+ - [...]
98
+
99
+ 8. Current Work:
100
+ [Precise description of current work]
101
+
102
+ 9. Optional Next Step:
103
+ [Optional Next step to take]
104
+
105
+ </summary>
106
+ </example>
107
+
108
+ Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
109
+
110
+ There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
111
+ <example>
112
+ ## Compact Instructions
113
+ When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
114
+ </example>
115
+
116
+ <example>
117
+ # Summary instructions
118
+ When you are using compact - please focus on test output and code changes. Include file reads verbatim.
119
+ </example>
120
+
121
+
122
+ REMINDER: Do NOT call any tools. Respond with plain text only — an <analysis> block followed by a <summary> block. Tool calls will be rejected and you will fail the task.`;
123
+
124
+ /**
125
+ * The full text of the appended user message: one <system-reminder> holding
126
+ * the trigger notice directly above the verbatim instruction, preceded by an
127
+ * optional "## Compact Instructions" reminder (the included-context
128
+ * affordance the instruction itself describes). A previous compaction's
129
+ * summary is NOT injected here: it is reattached upstream as the leading
130
+ * compactionSummary message, the exact shape the live context carries it in.
131
+ */
132
+ export function buildCompactionInstruction(options: {
133
+ reason: "manual" | "threshold" | "overflow";
134
+ customInstructions?: string;
135
+ }): string {
136
+ const notice =
137
+ options.reason === "manual"
138
+ ? "The user has triggered a /compact command to summarize this conversation to reduce token usage and reduce the context window."
139
+ : "The conversation context window is running out. You must summarize the conversation immediately so that work can continue in a fresh context.";
140
+ const parts: string[] = [];
141
+ if (options.customInstructions?.trim()) {
142
+ parts.push(`<system-reminder>\n## Compact Instructions\n${options.customInstructions.trim()}\n</system-reminder>`);
143
+ }
144
+ parts.push(`<system-reminder>\n${notice}\n${COMPACTION_INSTRUCTION}\n</system-reminder>`);
145
+ return parts.join("\n\n");
146
+ }
147
+
148
+ /**
149
+ * Claude Code's continuation preamble, baked into the *stored* summary so
150
+ * every future context — and the reattached compactionSummary message on a
151
+ * re-compaction — carries it. pi's own renderer then wraps the whole thing in
152
+ * its "compacted into the following summary: <summary>…</summary>" frame;
153
+ * that outer frame is hardcoded in pi's convertToLlm and not ours to change.
154
+ *
155
+ * The transcript pointer makes the summary's losses *recoverable*: a detail
156
+ * that did not survive summarization (an exact error message, a snippet, a
157
+ * command's real output) can be grepped out of the session JSONL instead of
158
+ * being gone. The warning matters as much as the path — the transcript is far
159
+ * larger than the context that was just freed, so reading it whole would
160
+ * undo the compaction.
161
+ */
162
+ export function continuationSummary(summary: string, transcriptPath?: string): string {
163
+ const preamble =
164
+ "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.";
165
+ const transcript = transcriptPath
166
+ ? `\n\nThe full transcript of the summarized conversation is at ${transcriptPath} (JSONL, one entry per line). It is far larger than your context — NEVER read it whole. If the summary is missing a specific detail you need, grep it for a distinctive string (an error message, a file path, a function name) or read a narrow line range.`
167
+ : "";
168
+ return `${preamble}\n${summary}${transcript}`;
169
+ }
170
+
171
+ /**
172
+ * The <summary> block is the surviving context; <analysis> is scratch work.
173
+ *
174
+ * Tags are matched at line starts: prose *mentions* the tags — the first live
175
+ * run's analysis said "wrapped in `<analysis>` and `<summary>` tags", the
176
+ * loose regex anchored on that mention, and the stored summary began with the
177
+ * tail of the analysis. Greedy to the last closing tag, so an embedded example
178
+ * cannot truncate the real block. A response without a well-formed block
179
+ * (small models drift) is used whole minus any analysis — losing the whole
180
+ * compaction over a formatting slip would hurt more than untidy text.
181
+ */
182
+ export function extractSummary(text: string): string | undefined {
183
+ const lineAnchored = text.match(/^[ \t]*<summary>[ \t]*\n([\s\S]*)\n[ \t]*<\/summary>[ \t]*$/m);
184
+ if (lineAnchored) return lineAnchored[1].trim() || undefined;
185
+ // Loose fallback, only after dropping analysis blocks so an inline mention
186
+ // there cannot become the anchor again.
187
+ const withoutAnalysis = text.replace(/<analysis>[\s\S]*?<\/analysis>/g, "");
188
+ const loose = withoutAnalysis.match(/<summary>([\s\S]*)<\/summary>/);
189
+ if (loose) return loose[1].trim() || undefined;
190
+ return withoutAnalysis.trim() || undefined;
191
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * context-management extension — asks Anthropic to drop old thinking blocks.
3
+ *
4
+ * Claude Code sends `context_management: { edits: [{ type: "clear_thinking_20251015",
5
+ * keep: "all" }] }` on every request, which keeps long sessions from carrying
6
+ * every past reasoning block. pi does not, so a long One Code session
7
+ * accumulates more context than Claude Code would.
8
+ *
9
+ * Two things the parameter needs, both found empirically against the live API
10
+ * (2026-08-05, api.anthropic.com):
11
+ *
12
+ * - The `anthropic-beta: context-management-2025-06-27` header, or the body
13
+ * param 400s with "context_management: Extra inputs are not permitted".
14
+ * Setting the header from `before_provider_headers` REPLACES the value pi
15
+ * computes at client creation (extension headers merge last), so we must
16
+ * rebuild pi's own beta list and append ours — see anthropicBetas(). That
17
+ * replicates pi-ai's createClient logic (pinned v0.83): OAuth identity betas,
18
+ * fine-grained tool streaming for models without eager input streaming, and
19
+ * interleaved thinking for non-adaptive models. Re-check on pi upgrades.
20
+ *
21
+ * - `thinking` enabled or an adaptive-thinking model, or the API 400s with
22
+ * "`clear_thinking_20251015` strategy requires `thinking` to be enabled or
23
+ * adaptive". The payload hook checks before attaching the edit.
24
+ *
25
+ * ON BY DEFAULT for first-party Anthropic (provider `anthropic`,
26
+ * api.anthropic.com) — verified there, and Claude Code sends it on every
27
+ * request. OFF everywhere else: Bedrock takes `anthropic_beta` in the body,
28
+ * not the header, and proxies may strip unknown params — a rejected parameter
29
+ * fails every request. `CC_CLEAR_THINKING=0` forces it off; `=1` forces it on
30
+ * for an anthropic-messages endpoint you have confirmed accepts it.
31
+ */
32
+
33
+ import { readFileSync, statSync } from "node:fs";
34
+ import { join } from "node:path";
35
+ import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
36
+
37
+ const CLEAR_THINKING_EDIT = { type: "clear_thinking_20251015", keep: "all" };
38
+ const CONTEXT_MANAGEMENT_BETA = "context-management-2025-06-27";
39
+
40
+ // pi-ai's own beta features (anthropic-messages.ts, v0.83) — rebuilt here
41
+ // because our header value replaces the one pi computes.
42
+ const OAUTH_BETAS = ["claude-code-20250219", "oauth-2025-04-20"];
43
+ const FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";
44
+ const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
45
+
46
+ export interface AnthropicModelCompat {
47
+ forceAdaptiveThinking?: boolean;
48
+ supportsEagerToolInputStreaming?: boolean;
49
+ }
50
+
51
+ /** pi's beta list for this model/auth, with the context-management beta appended. */
52
+ export function anthropicBetas(oauth: boolean, compat: AnthropicModelCompat | undefined): string {
53
+ const betas: string[] = [];
54
+ if (oauth) betas.push(...OAUTH_BETAS);
55
+ // pi sends this only when tools are present; we always register tools.
56
+ if (compat?.supportsEagerToolInputStreaming === false) betas.push(FINE_GRAINED_TOOL_STREAMING_BETA);
57
+ if (compat?.forceAdaptiveThinking !== true) betas.push(INTERLEAVED_THINKING_BETA);
58
+ betas.push(CONTEXT_MANAGEMENT_BETA);
59
+ return betas.join(",");
60
+ }
61
+
62
+ /** Anthropic Messages API shape: `messages` + `max_tokens`, and not an OpenAI `input`. */
63
+ export function looksLikeAnthropicRequest(payload: unknown): boolean {
64
+ if (!payload || typeof payload !== "object") return false;
65
+ const record = payload as Record<string, unknown>;
66
+ if (!Array.isArray(record.messages)) return false;
67
+ if ("input" in record) return false;
68
+ const model = typeof record.model === "string" ? record.model : "";
69
+ return model.includes("claude") || typeof record.max_tokens === "number";
70
+ }
71
+
72
+ /** The edit is rejected unless thinking is enabled or the model is adaptive. */
73
+ export function clearThinkingApplies(payload: Record<string, unknown>, forceAdaptiveThinking: boolean): boolean {
74
+ return payload.thinking !== undefined || forceAdaptiveThinking;
75
+ }
76
+
77
+ export function withClearThinking(payload: Record<string, unknown>): Record<string, unknown> {
78
+ const existing = payload.context_management as { edits?: unknown[] } | undefined;
79
+ if (existing?.edits?.some((edit) => (edit as { type?: string })?.type === CLEAR_THINKING_EDIT.type)) {
80
+ return payload;
81
+ }
82
+ return {
83
+ ...payload,
84
+ context_management: { edits: [...(existing?.edits ?? []), CLEAR_THINKING_EDIT] },
85
+ };
86
+ }
87
+
88
+ /** mtime cache: this runs on every provider request, the hottest path there is. */
89
+ let authCache: { mtimeMs: number; oauth: boolean } | undefined;
90
+
91
+ /** OAuth logins need pi's identity betas kept in the header we overwrite. */
92
+ export function isAnthropicOAuth(): boolean {
93
+ // getAgentDir() honours PI_CODING_AGENT_DIR, so an isolated one-code app
94
+ // reads its own auth.json rather than ~/.pi's.
95
+ const path = join(getAgentDir(), "auth.json");
96
+ try {
97
+ const mtimeMs = statSync(path).mtimeMs;
98
+ const cached = authCache;
99
+ if (cached && cached.mtimeMs === mtimeMs) return cached.oauth;
100
+ const auth = JSON.parse(readFileSync(path, "utf8"));
101
+ const entry = auth?.anthropic;
102
+ const oauth = entry?.type === "oauth" || typeof entry?.refresh === "string";
103
+ authCache = { mtimeMs, oauth };
104
+ return oauth;
105
+ } catch {
106
+ authCache = undefined;
107
+ return false;
108
+ }
109
+ }
110
+
111
+ interface AnthropicishModel {
112
+ api?: string;
113
+ provider?: string;
114
+ baseUrl?: string;
115
+ compat?: AnthropicModelCompat;
116
+ }
117
+
118
+ /**
119
+ * Default-on only where verified: first-party Anthropic. The env var overrides
120
+ * both ways so a proxy user can opt in and anyone can opt out. Checked per
121
+ * request because the model can change mid-session.
122
+ */
123
+ export function clearThinkingEnabled(flag: string | undefined, model: AnthropicishModel | undefined): boolean {
124
+ if (model?.api !== "anthropic-messages") return false;
125
+ if (flag === "0") return false;
126
+ if (flag === "1") return true;
127
+ return model.provider === "anthropic" && (model.baseUrl ?? "").includes("api.anthropic.com");
128
+ }
129
+
130
+ export default function contextManagementExtension(pi: ExtensionAPI) {
131
+ const flag = () => process.env.CC_CLEAR_THINKING;
132
+
133
+ pi.on("before_provider_headers", (event, ctx) => {
134
+ const model = ctx.model as AnthropicishModel | undefined;
135
+ if (!clearThinkingEnabled(flag(), model)) return;
136
+ event.headers["anthropic-beta"] = anthropicBetas(isAnthropicOAuth(), model?.compat);
137
+ });
138
+
139
+ pi.on("before_provider_request", (event, ctx) => {
140
+ const model = ctx.model as AnthropicishModel | undefined;
141
+ if (!clearThinkingEnabled(flag(), model)) return undefined;
142
+ if (!looksLikeAnthropicRequest(event.payload)) return undefined;
143
+ const payload = event.payload as Record<string, unknown>;
144
+ if (!clearThinkingApplies(payload, model?.compat?.forceAdaptiveThinking === true)) return undefined;
145
+ return withClearThinking(payload);
146
+ });
147
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * effort extension — Claude Code's `/effort`, including the `ultracode` stop.
3
+ *
4
+ * Reasoning effort is pi's thinking level under another name, and shift+tab
5
+ * already cycles it. pi reserves that key (`app.thinking.cycle` is on its
6
+ * RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS list, so `registerShortcut` on
7
+ * shift+tab is skipped with a warning), which settles the design: we cannot
8
+ * retarget or disable it, so the slider covers the same ladder it cycles rather
9
+ * than a different one, and both are presented as "effort" — pi's own wording
10
+ * for the dial stays visible in its footer, but nothing we write calls it
11
+ * "thinking".
12
+ *
13
+ * What the slider adds is the stop past the top: `ultracode`, the top reasoning
14
+ * level *plus* standing multi-agent orchestration. The keyword in a message arms
15
+ * one turn (see `extensions/workflow`); this mode arms every turn until it is
16
+ * switched off, via an `every-turn` reminder keyed so it can be withdrawn — the
17
+ * same shape the permissions extension uses for plan mode.
18
+ */
19
+
20
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
21
+ import { getSupportedThinkingLevels } from "@earendil-works/pi-ai/compat";
22
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
23
+ import { REMINDER_CHANNEL } from "../lib/reminders.ts";
24
+ import { safeThemePaint } from "../lib/tui-render.ts";
25
+ import {
26
+ acceptedEffortArgs,
27
+ choiceForState,
28
+ decodeKey,
29
+ type EffortChoice,
30
+ EFFORT_CHOICES,
31
+ enabledStops,
32
+ levelRank,
33
+ moveIndex,
34
+ nearestEnabled,
35
+ parseEffortArg,
36
+ renderEffortSlider,
37
+ THINKING_LEVELS,
38
+ thinkingLevelFor,
39
+ ULTRACODE,
40
+ ULTRACODE_LEVEL,
41
+ } from "./slider.ts";
42
+
43
+ /** The levels pi says the active model can reach; the full ladder when unknown. */
44
+ function supportedLevels(ctx: ExtensionContext): ThinkingLevel[] {
45
+ return ctx.model ? (getSupportedThinkingLevels(ctx.model) as ThinkingLevel[]) : [...THINKING_LEVELS];
46
+ }
47
+
48
+ /** A short name for the model, for messages that name what does/doesn't support a level. */
49
+ function modelLabel(ctx: ExtensionContext): string {
50
+ return ctx.model?.name ?? ctx.model?.id ?? "this model";
51
+ }
52
+
53
+ const REMINDER_KEY = "ultracode-mode";
54
+ const STATUS_KEY = "ultracode";
55
+
56
+ /**
57
+ * The standing instruction for ultracode mode. Deliberately stronger than the
58
+ * single-turn keyword reminder: it makes orchestration the default for
59
+ * substantive work rather than something to consider, and still carves out the
60
+ * trivial cases so the mode does not spawn a fleet to rename a variable.
61
+ */
62
+ const ULTRACODE_STANDING_REMINDER =
63
+ "Ultracode mode is on, so the user's opt-in to multi-agent orchestration is standing: author and run a workflow for every substantive task by default, and lean toward adversarially verifying your findings. " +
64
+ "For multi-phase work (understand → design → implement → review) that often means several workflows in sequence — one per phase — so you stay in the loop between them. " +
65
+ "Token cost is not the constraint here; the most exhaustive correct answer is. " +
66
+ "Work solo only on conversational turns and trivial mechanical edits.";
67
+
68
+ export default function effortExtension(pi: ExtensionAPI) {
69
+ let ultracodeActive = false;
70
+ /**
71
+ * The level ultracode actually settled on. Not always xhigh: pi clamps to
72
+ * model capability, so on a model that caps lower this is that cap — and the
73
+ * shift+tab hygiene below must compare against it, or the mode would drop
74
+ * itself the moment anything re-announced the clamped level.
75
+ */
76
+ let ultracodeLevel: ThinkingLevel | undefined;
77
+
78
+ const applyStatus = (ctx: ExtensionContext) => {
79
+ // No-op outside the TUI, so this is safe to call unconditionally.
80
+ ctx.ui.setStatus(STATUS_KEY, ultracodeActive ? "✦ ultracode" : undefined);
81
+ };
82
+
83
+ const setUltracode = (on: boolean, level?: ThinkingLevel) => {
84
+ ultracodeActive = on;
85
+ ultracodeLevel = on ? level : undefined;
86
+ if (on) {
87
+ pi.events.emit(REMINDER_CHANNEL, {
88
+ text: ULTRACODE_STANDING_REMINDER,
89
+ scope: "every-turn",
90
+ key: REMINDER_KEY,
91
+ });
92
+ } else {
93
+ pi.events.emit(REMINDER_CHANNEL, { remove: true, key: REMINDER_KEY });
94
+ }
95
+ };
96
+
97
+ /** Apply a chosen stop and report what actually took effect. */
98
+ const applyChoice = (choice: EffortChoice, ctx: ExtensionContext) => {
99
+ const wanted = thinkingLevelFor(choice);
100
+ pi.setThinkingLevel(wanted);
101
+ const actual = pi.getThinkingLevel();
102
+
103
+ setUltracode(choice === ULTRACODE, actual);
104
+ applyStatus(ctx);
105
+
106
+ // setThinkingLevel clamps to model capability silently. Only flag a genuine
107
+ // downward clamp (the model can't reach the requested level); an upward clamp
108
+ // toward the model's floor isn't a "cap" and saying so reads as a bug.
109
+ const wr = levelRank(wanted);
110
+ const ar = levelRank(actual);
111
+ const cappedDown = ar >= 0 && wr >= 0 && ar < wr;
112
+ const note = cappedDown ? ` (${modelLabel(ctx)} tops out at ${actual})` : "";
113
+ if (choice === ULTRACODE) {
114
+ ctx.ui.notify(`Effort: ultracode — ${actual} reasoning, workflows armed every turn${note}`, "info");
115
+ } else {
116
+ ctx.ui.notify(`Effort: ${actual}${note}`, "info");
117
+ }
118
+ };
119
+
120
+ const showSlider = async (ctx: ExtensionContext): Promise<void> => {
121
+ const supported = supportedLevels(ctx);
122
+ if (!supported.some((level) => level !== "off")) {
123
+ ctx.ui.notify(`${modelLabel(ctx)} doesn't support reasoning effort.`, "info");
124
+ return;
125
+ }
126
+ const enabled = enabledStops(supported);
127
+
128
+ // Start on the current stop, snapped onto a stop this model can actually
129
+ // reach so the marker never opens on a dimmed, unselectable level.
130
+ let index = EFFORT_CHOICES.indexOf(choiceForState(pi.getThinkingLevel(), ultracodeActive));
131
+ if (index < 0) index = 0;
132
+ index = nearestEnabled(index, enabled);
133
+
134
+ const label = modelLabel(ctx);
135
+ const chosen = await ctx.ui.custom<EffortChoice | null>((tui, theme, _keybindings, done) => {
136
+ const paint = safeThemePaint(theme);
137
+ return {
138
+ render: (width: number) => ["", ...renderEffortSlider({ index, enabled, width, modelLabel: label }, paint), ""],
139
+ handleInput: (data: string) => {
140
+ const key = decodeKey(data);
141
+ if (!key) return;
142
+ if (key === "cancel") {
143
+ done(null);
144
+ return;
145
+ }
146
+ if (key === "confirm") {
147
+ done(EFFORT_CHOICES[index]);
148
+ return;
149
+ }
150
+ index = moveIndex(index, key, enabled);
151
+ tui.requestRender();
152
+ },
153
+ invalidate: () => {},
154
+ };
155
+ });
156
+
157
+ if (chosen) applyChoice(chosen, ctx);
158
+ };
159
+
160
+ pi.registerCommand("effort", {
161
+ description: `Set reasoning effort (shift+tab cycles the plain levels): /effort [${EFFORT_CHOICES.join("|")}] — ultracode is ${ULTRACODE_LEVEL} + workflows`,
162
+ getArgumentCompletions: (prefix) => {
163
+ const matches = acceptedEffortArgs().filter((value) => value.startsWith(prefix.trim().toLowerCase()));
164
+ return matches.length ? matches.map((value) => ({ value, label: value })) : null;
165
+ },
166
+ handler: async (args, ctx) => {
167
+ const typed = args.trim();
168
+ if (typed) {
169
+ const parsed = parseEffortArg(typed);
170
+ if (!parsed) {
171
+ ctx.ui.notify(`Unknown effort "${typed}". Use one of: ${acceptedEffortArgs().join(", ")}`, "error");
172
+ return;
173
+ }
174
+ // A plain level the model can't reach would silently clamp to something
175
+ // else; refuse it and name what this model does support instead.
176
+ if (parsed !== ULTRACODE) {
177
+ const supported = supportedLevels(ctx);
178
+ if (!supported.includes(parsed as ThinkingLevel)) {
179
+ ctx.ui.notify(
180
+ `Effort "${parsed}" isn't supported by ${modelLabel(ctx)} — it supports ${supported.join(", ")} (shift+tab cycles these).`,
181
+ "error",
182
+ );
183
+ return;
184
+ }
185
+ }
186
+ applyChoice(parsed, ctx);
187
+ return;
188
+ }
189
+
190
+ // The picker needs focus and a terminal; elsewhere say what to type.
191
+ if (!ctx.hasUI || ctx.mode !== "tui") {
192
+ ctx.ui.notify(
193
+ `Current effort: ${ultracodeActive ? `ultracode (${pi.getThinkingLevel()} + workflows)` : pi.getThinkingLevel()}. ` +
194
+ `Set one with /effort <${acceptedEffortArgs().join("|")}>.`,
195
+ "info",
196
+ );
197
+ return;
198
+ }
199
+ await showSlider(ctx);
200
+ },
201
+ });
202
+
203
+ // Cycling thinking with shift+tab away from ultracode's level makes the
204
+ // footer indicator a lie, so drop the mode instead of letting the two drift.
205
+ pi.on("thinking_level_select", (event, ctx) => {
206
+ if (ultracodeActive && ultracodeLevel !== undefined && event.level !== ultracodeLevel) {
207
+ setUltracode(false);
208
+ applyStatus(ctx);
209
+ ctx.ui.notify(`Ultracode off — reasoning is now ${event.level}`, "info");
210
+ }
211
+ });
212
+
213
+ pi.on("session_start", (_event, ctx) => {
214
+ applyStatus(ctx);
215
+ });
216
+ }