pal-code 0.0.9 → 0.0.11

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 (47) hide show
  1. package/README.md +3 -3
  2. package/SYSTEM.md +3 -3
  3. package/bin/pal-code.js +37 -11
  4. package/package.json +7 -14
  5. package/packages/cli/README.md +2 -2
  6. package/packages/cli/src/commands/ext.ts +1 -1
  7. package/packages/cli/src/commands.ts +1 -1
  8. package/packages/cli/src/components/render-history.ts +2 -2
  9. package/packages/cli/src/config.ts +2 -2
  10. package/packages/cli/src/index.ts +7 -7
  11. package/packages/cli/src/overlays/key-input.ts +1 -1
  12. package/packages/cli/src/overlays/model-picker.ts +2 -2
  13. package/packages/cli/src/overlays/session-picker.ts +1 -1
  14. package/packages/cli/src/overlays/wizard.ts +1 -1
  15. package/packages/cli/src/state.ts +2 -2
  16. package/packages/cli/src/turn.ts +16 -9
  17. package/packages/cli/src/utils/permissions.ts +3 -3
  18. package/packages/core/src/agent/events.ts +0 -36
  19. package/packages/core/src/agent/fallback.ts +0 -344
  20. package/packages/core/src/agent/index.ts +0 -35
  21. package/packages/core/src/agent/roles.ts +0 -188
  22. package/packages/core/src/agent/run.ts +0 -713
  23. package/packages/core/src/agent/scope.ts +0 -34
  24. package/packages/core/src/agent/todos.ts +0 -66
  25. package/packages/core/src/compaction.ts +0 -243
  26. package/packages/core/src/config.ts +0 -387
  27. package/packages/core/src/extensions.ts +0 -178
  28. package/packages/core/src/index.ts +0 -157
  29. package/packages/core/src/logger.ts +0 -54
  30. package/packages/core/src/provider/auth.ts +0 -153
  31. package/packages/core/src/provider/complete.ts +0 -63
  32. package/packages/core/src/provider/index.ts +0 -6
  33. package/packages/core/src/provider/openrouter.ts +0 -304
  34. package/packages/core/src/provider/pick-model.ts +0 -43
  35. package/packages/core/src/provider/registry.ts +0 -222
  36. package/packages/core/src/provider/types.ts +0 -61
  37. package/packages/core/src/repo-map.ts +0 -177
  38. package/packages/core/src/session/index.ts +0 -2
  39. package/packages/core/src/session/store.ts +0 -677
  40. package/packages/core/src/session/types.ts +0 -72
  41. package/packages/core/src/snapshots.ts +0 -107
  42. package/packages/core/src/tools/definitions.ts +0 -365
  43. package/packages/core/src/tools/executor.ts +0 -1363
  44. package/packages/core/src/tools/index.ts +0 -5
  45. package/packages/core/src/tools/search.ts +0 -201
  46. package/scripts/postinstall.js +0 -121
  47. package/scripts/preinstall.js +0 -51
@@ -1,34 +0,0 @@
1
- /**
2
- * Run scope — snapshot/restore of the mutable module state a nested run could
3
- * clobber.
4
- *
5
- * core keeps a little module-level state for ergonomics (the todo list, the
6
- * tracked shell cwd). That's fine for a single interactive turn, but `delegate`
7
- * starts a *nested* run inside the same process: a child that calls `todo` or
8
- * `cd`s would silently overwrite the parent's plan and working directory.
9
- *
10
- * Wrapping the child in capture/restore keeps the two runs isolated without
11
- * threading a context object through every tool signature.
12
- */
13
-
14
- import {getTodos, restoreTodos, type Todo} from './todos.js';
15
- import {getShellCwd, setShellCwd} from '../tools/executor.js';
16
-
17
- export interface RunScope {
18
- todos: Todo[];
19
- shellCwd: string;
20
- }
21
-
22
- /** Capture the state a nested run must not leak into its parent. */
23
- export function captureRunScope(): RunScope {
24
- return {
25
- todos: getTodos().map((t) => ({...t})),
26
- shellCwd: getShellCwd(),
27
- };
28
- }
29
-
30
- /** Restore a scope captured by `captureRunScope`. Safe to call in a `finally`. */
31
- export function restoreRunScope(scope: RunScope): void {
32
- restoreTodos(scope.todos);
33
- setShellCwd(scope.shellCwd);
34
- }
@@ -1,66 +0,0 @@
1
- /**
2
- * Task plan for multi-step work.
3
- *
4
- * The model writes the full list on every `todo` call (replace semantics, like
5
- * OpenCode's todowrite). Keeping the list in one place lets the UI render live
6
- * progress and lets the model see "am I done?" without re-exploring.
7
- */
8
-
9
- export type TodoStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled';
10
-
11
- export interface Todo {
12
- content: string;
13
- status: TodoStatus;
14
- }
15
-
16
- const VALID_STATUS: readonly TodoStatus[] = ['pending', 'in_progress', 'completed', 'cancelled'];
17
-
18
- let todos: Todo[] = [];
19
-
20
- /** Replace the whole list. Returns the normalised list. */
21
- export function setTodos(next: readonly Todo[]): Todo[] {
22
- todos = next
23
- .filter((t) => t && typeof t.content === 'string' && t.content.trim().length > 0)
24
- .map((t) => ({
25
- content: t.content.trim().slice(0, 200),
26
- status: VALID_STATUS.includes(t.status) ? t.status : 'pending',
27
- }))
28
- .slice(0, 50);
29
- return todos;
30
- }
31
-
32
- /** Current list (live reference — treat as read-only). */
33
- export function getTodos(): readonly Todo[] {
34
- return todos;
35
- }
36
-
37
- /** Drop all items (new session / clear). */
38
- export function clearTodos(): void {
39
- todos = [];
40
- }
41
-
42
- /**
43
- * Copy of the current list, for restoring after a nested run (`delegate`)
44
- * that used `todo` and would otherwise clobber the parent's plan.
45
- */
46
- export function snapshotTodos(): Todo[] {
47
- return todos.map((t) => ({...t}));
48
- }
49
-
50
- /** Restore a snapshot taken by `snapshotTodos`. */
51
- export function restoreTodos(snapshot: readonly Todo[]): void {
52
- todos = snapshot.map((t) => ({...t}));
53
- }
54
-
55
- /** Compact one-line-per-item rendering used as the tool result. */
56
- export function formatTodos(list: readonly Todo[] = todos): string {
57
- if (list.length === 0) return '(no todos)';
58
- const mark: Record<TodoStatus, string> = {
59
- pending: '[ ]',
60
- in_progress: '[~]',
61
- completed: '[x]',
62
- cancelled: '[-]',
63
- };
64
- const done = list.filter((t) => t.status === 'completed').length;
65
- return `${done}/${list.length} done\n${list.map((t) => `${mark[t.status]} ${t.content}`).join('\n')}`;
66
- }
@@ -1,243 +0,0 @@
1
- // Structural message shape — works with both the CLI's local Message union
2
- // and the provider Message type. Only needs role/content/toolCalls.
3
- export interface CompactableMessage {
4
- role: string;
5
- content: string;
6
- toolCalls?: Array<{
7
- id: string;
8
- name: string;
9
- arguments: string;
10
- extraContent?: Record<string, unknown>;
11
- }>;
12
- tool_call_id?: string;
13
- }
14
-
15
- const CHARS_PER_TOKEN = 4;
16
-
17
- /** Estimates the token count for the given text. */
18
- export function estimateTokens(text: string): number {
19
- return Math.ceil(text.length / CHARS_PER_TOKEN);
20
- }
21
-
22
- export function estimateMessagesTokens(messages: CompactableMessage[]): number {
23
- return messages.reduce((sum, m) => {
24
- let tokens = estimateTokens(m.content || '') + 4;
25
- // Count tool-call arguments — a transcript dominated by large write_file
26
- // bodies or long bash commands would otherwise under-count massively.
27
- if (m.toolCalls) {
28
- for (const tc of m.toolCalls) {
29
- tokens += estimateTokens(tc.arguments);
30
- }
31
- }
32
- return sum + tokens;
33
- }, 0);
34
- }
35
-
36
- export interface CompactionConfig {
37
- maxTokens: number;
38
- reservedTokens: number;
39
- }
40
-
41
- export function shouldCompact(messages: CompactableMessage[], config: CompactionConfig): boolean {
42
- const used = estimateMessagesTokens(messages);
43
- return used > config.maxTokens - config.reservedTokens;
44
- }
45
-
46
- const KEEP_RECENT = 5;
47
- const TOOL_TRUNCATE = 200;
48
- const ASSISTANT_TRUNCATE = 500;
49
-
50
- export function compactMessages<T extends CompactableMessage>(
51
- messages: T[],
52
- config: CompactionConfig,
53
- ): {messages: T[]; summary: string} {
54
- if (!shouldCompact(messages, config)) {
55
- return {messages, summary: ''};
56
- }
57
-
58
- if (messages.length <= KEEP_RECENT + 1) {
59
- return compactToolResults(messages);
60
- }
61
-
62
- // Never inject a synthetic `system` message mid-conversation: the caller owns
63
- // the system prompt. If the caller already stored it as the first message,
64
- // fold the compaction note into that single system message instead.
65
- const hasSystem = messages[0]?.role === 'system';
66
- const body = hasSystem ? messages.slice(1) : messages;
67
- // The old/recent split must never fall between an assistant message that
68
- // carries `tool_calls` and the `tool` messages answering it. If it does, the
69
- // trimmed half keeps one side and drops the other, and the provider rejects
70
- // the history with a 400 ("assistant message with 'tool_calls' must be
71
- // followed by tool messages responding to each 'tool_call_id'").
72
- // Walk the boundary backwards until it sits at a clean group edge.
73
- const split = safeSplitIndex(body, body.length - KEEP_RECENT);
74
- const old = body.slice(0, split);
75
- const recent = body.slice(split);
76
-
77
- const summary = `[Context compacted: ${old.length} older messages truncated to save tokens]`;
78
-
79
- const compacted = old.map((m) => {
80
- if (m.role === 'tool') {
81
- return {...m, content: truncateContent(m.content, TOOL_TRUNCATE)};
82
- }
83
- if (m.role === 'assistant' && m.toolCalls) {
84
- return {
85
- ...m,
86
- content: truncateContent(m.content, 100),
87
- };
88
- }
89
- if (m.role === 'assistant' && m.content) {
90
- return {...m, content: truncateContent(m.content, ASSISTANT_TRUNCATE)};
91
- }
92
- return m;
93
- });
94
-
95
- if (hasSystem) {
96
- const system = messages[0];
97
- const mergedSystem: T = {
98
- ...system,
99
- content: system.content ? `${system.content}\n\n${summary}` : summary,
100
- };
101
- return {messages: [mergedSystem, ...compacted, ...recent], summary};
102
- }
103
-
104
- return {messages: [...compacted, ...recent], summary};
105
- }
106
-
107
- /**
108
- * Adjust an old/recent split point so it never lands inside a tool-call group.
109
- *
110
- * A group is an `assistant` message with `toolCalls` followed by one `tool`
111
- * message per call. Slicing through the middle of that group leaves the two
112
- * halves inconsistent — the provider then rejects the request with a 400.
113
- *
114
- * We move the boundary *backwards* to the start of the group, so the whole
115
- * group stays in `recent` (kept verbatim) rather than being split.
116
- */
117
- function safeSplitIndex(messages: CompactableMessage[], split: number): number {
118
- let i = Math.max(0, Math.min(split, messages.length));
119
- // If the first message of `recent` is a `tool` result, its owning assistant
120
- // call is just before the boundary — walk back to include it.
121
- while (i > 0 && messages[i]?.role === 'tool') i--;
122
- return i;
123
- }
124
-
125
- function compactToolResults<T extends CompactableMessage>(
126
- messages: T[],
127
- ): {messages: T[]; summary: string} {
128
- const compacted = messages.map((m) => {
129
- if (m.role === 'tool' && m.content && estimateTokens(m.content) > TOOL_TRUNCATE) {
130
- return {...m, content: truncateContent(m.content, TOOL_TRUNCATE)};
131
- }
132
- return m;
133
- });
134
- return {messages: compacted, summary: '[Large tool results truncated]'};
135
- }
136
-
137
- function truncateContent(content: string, maxChars: number): string {
138
- if (!content || content.length <= maxChars) return content;
139
- return (
140
- content.slice(0, maxChars) + `\n... [truncated, ${content.length - maxChars} chars removed]`
141
- );
142
- }
143
-
144
- // ---------------------------------------------------------------------------
145
- // Model view — the ONLY thing sent to the provider
146
- // ---------------------------------------------------------------------------
147
-
148
- export interface ModelView<T extends CompactableMessage> {
149
- /** Messages the model should see (everything after the high-water mark). */
150
- messages: T[];
151
- /** Summary text to fold into the system prompt ('' when nothing compacted). */
152
- note: string;
153
- }
154
-
155
- /**
156
- * Build the view the model is fed.
157
- *
158
- * This is the single source of truth for "what the model sees": the compaction
159
- * trigger, the persisted high-water mark, and the request payload must all agree,
160
- * otherwise the boundary drifts and we either resend summarized history or drop
161
- * unsummarized turns.
162
- *
163
- * `compactedUpto` is a COUNT of leading messages already folded into `note`
164
- * (1-based seq equivalence). Everything at or below it is replaced by the note;
165
- * everything above it is sent verbatim.
166
- */
167
- export function buildModelView<T extends CompactableMessage>(
168
- messages: readonly T[],
169
- compactedUpto: number,
170
- note: string,
171
- ): ModelView<T> {
172
- if (compactedUpto <= 0) return {messages: messages as T[], note: ''};
173
- const kept = (messages as T[]).slice(Math.min(compactedUpto, messages.length));
174
- return {messages: kept, note};
175
- }
176
-
177
- // ---------------------------------------------------------------------------
178
- // LLM-backed summarization
179
- // ---------------------------------------------------------------------------
180
-
181
- /** Minimal provider surface needed to summarize (keeps this module provider-free). */
182
- export interface Summarizer {
183
- (prompt: string): Promise<string>;
184
- }
185
-
186
- const SUMMARY_SYSTEM_PROMPT =
187
- 'You compress coding-agent conversation history. Produce a dense, factual ' +
188
- 'summary that preserves decisions made, files changed, commands run, errors ' +
189
- 'encountered, and any constraints or preferences the user stated. Omit ' +
190
- 'pleasantries and redundant tool output. Write in compact prose or bullets. ' +
191
- 'Do not address the user; this summary replaces the messages it describes.';
192
-
193
- /**
194
- * Summarize a range of older messages into a checkpoint string.
195
- *
196
- * Falls back to a deterministic truncation summary when the model call fails,
197
- * so a flaky provider never aborts the turn (the worst case is a less useful —
198
- * but still valid — checkpoint).
199
- */
200
- export async function summarizeRange(
201
- messages: readonly CompactableMessage[],
202
- summarize: Summarizer,
203
- ): Promise<string> {
204
- const transcript = messages
205
- .map((m) => {
206
- const role = m.role === 'tool' ? 'tool' : m.role;
207
- const body = m.content?.trim() ? m.content.trim() : '(no text)';
208
- const calls = m.toolCalls?.length
209
- ? `\n[tool calls: ${m.toolCalls.map((c) => c.name).join(', ')}]`
210
- : '';
211
- return `<${role}>\n${body}${calls}`;
212
- })
213
- .join('\n\n');
214
-
215
- const prompt = `${SUMMARY_SYSTEM_PROMPT}\n\n---\n\nConversation to summarize:\n\n${transcript}`;
216
-
217
- try {
218
- const summary = (await summarize(prompt)).trim();
219
- if (summary) return summary;
220
- } catch {
221
- // fall through to the deterministic fallback
222
- }
223
-
224
- return `[Context compacted: ${messages.length} older messages summarized]`;
225
- }
226
-
227
- /**
228
- * Pick the seq boundary to compact up to, without ever splitting a tool-call
229
- * group. Returns the count of leading messages that may be summarized away.
230
- *
231
- * The boundary is walked backwards over `tool` messages so an assistant message
232
- * carrying `tool_calls` is never separated from the results answering it — the
233
- * exact rule `sanitizeWireMessages` enforces at the wire.
234
- */
235
- export function compactionBoundary<T extends CompactableMessage>(
236
- messages: readonly T[],
237
- keepRecent: number,
238
- ): number {
239
- let split = Math.max(0, messages.length - keepRecent);
240
- while (split > 0 && messages[split]?.role === 'tool') split--;
241
- return split;
242
- }
243
-