@pal-code/core 0.0.21 → 0.0.23

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pal-code/core",
3
- "version": "0.0.21",
3
+ "version": "0.0.23",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/src/agent/run.ts CHANGED
@@ -12,6 +12,8 @@ import {getDiagnosticsMode, takeDiagnosticsLine} from '../diagnostics.js';
12
12
  import {emitLifecycleEvent, type TurnContext} from '../lifecycle.js';
13
13
  import {complete} from '../provider/complete.js';
14
14
  import type {Provider, StreamEvent} from '../provider/types.js';
15
+ import type {Effort} from '../provider/effort.js';
16
+ import {DEFAULT_REASONING_EFFORT} from '../app-config.js';
15
17
  import {getMaxParallel} from './roles.js';
16
18
 
17
19
  // ---------------------------------------------------------------------------
@@ -148,8 +150,8 @@ export interface RunAgentOptions {
148
150
  budget?: {roleName: string; limit: number};
149
151
  /** Context window used to decide when to compact (default 200_000). */
150
152
  contextLimit?: number;
151
- /** Reasoning effort forwarded to the provider (default 'medium'). */
152
- reasoningEffort?: 'low' | 'medium' | 'high';
153
+ /** Reasoning effort forwarded to the provider (default `high`). */
154
+ reasoningEffort?: Effort;
153
155
  /**
154
156
  * High-water mark of genuinely-uncompacted history, as a 1-based store seq.
155
157
  * Messages at seq `<= compactedSeq` have already been folded into a persisted
@@ -273,24 +275,12 @@ export function summarizeArgs(name: string, args: Record<string, unknown>): stri
273
275
  }
274
276
  }
275
277
 
276
- /** Provider-specific reasoning/thinking parameters. */
277
- export function getEffortParams(
278
- model: string,
279
- effort: 'low' | 'medium' | 'high',
280
- ): Record<string, unknown> {
281
- if (/^o[134]/.test(model) || model.includes('gpt-5') || model.includes('gpt-6')) {
282
- return {reasoning_effort: effort};
283
- }
284
- if (model.startsWith('claude') || model.includes('anthropic') || model.includes('fable')) {
285
- const budget = effort === 'low' ? 2000 : effort === 'medium' ? 8000 : 16000;
286
- return {thinking: {type: 'enabled', budget_tokens: budget}};
287
- }
288
- if (model.startsWith('gemini')) {
289
- const budget = effort === 'low' ? 1024 : effort === 'medium' ? 8192 : 24576;
290
- return {generationConfig: {thinkingConfig: {thinkingBudget: budget}}};
291
- }
292
- return {};
293
- }
278
+ // `getEffortParams` now lives in `provider/effort.ts`, where it is
279
+ // protocol-aware. Re-exported so existing importers keep working.
280
+ export {getEffortParams} from '../provider/effort.js';
281
+
282
+ /** Process default, applied when `reasoningEffort` is omitted (see app-config). */
283
+ export const DEFAULT_EFFORT: Effort = DEFAULT_REASONING_EFFORT;
294
284
 
295
285
  /** Map the conversation to the OpenAI-compatible wire format. */
296
286
  /**
@@ -516,7 +506,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
516
506
  systemPrompt,
517
507
  maxRounds = DEFAULT_MAX_ROUNDS,
518
508
  contextLimit = DEFAULT_CONTEXT_LIMIT,
519
- reasoningEffort = 'medium',
509
+ reasoningEffort = DEFAULT_REASONING_EFFORT,
520
510
  providerConfig,
521
511
  executeTool,
522
512
  budget,
@@ -646,8 +636,10 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
646
636
  messages: apiMessages,
647
637
  tools: tools as never,
648
638
  signal,
649
- ...getEffortParams(model, reasoningEffort),
650
- } as never) as AsyncGenerator<StreamEvent>) {
639
+ // Effort is an *intent*; the provider translates it to the wire shape of
640
+ // whichever protocol it routes this model to (see provider/effort.ts).
641
+ effort: reasoningEffort,
642
+ })) {
651
643
  if (event.type === 'text' && event.content) {
652
644
  if (thinkingMs === null && thinkingStart !== null) thinkingMs = Date.now() - thinkingStart;
653
645
  textContent += event.content;
@@ -844,8 +836,8 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
844
836
  messages: buildApiMessages(messages, systemPrompt, compactionNote, compactedUpto),
845
837
  tools: [] as never,
846
838
  signal,
847
- ...getEffortParams(model, reasoningEffort),
848
- } as never) as AsyncGenerator<StreamEvent>) {
839
+ effort: reasoningEffort,
840
+ })) {
849
841
  if (event.type === 'text' && event.content) {
850
842
  wrapText += event.content;
851
843
  yield {type: 'text-delta', content: event.content};
@@ -12,11 +12,18 @@
12
12
  */
13
13
 
14
14
  import {getTodos, restoreTodos, type Todo} from './todos.js';
15
- import {getShellCwd, setShellCwd} from '../tools/executor.js';
15
+ import {getShellCwd, getShellRoot, setShellCwd, setShellRoot} from '../tools/executor.js';
16
16
 
17
17
  export interface RunScope {
18
18
  todos: Todo[];
19
19
  shellCwd: string;
20
+ /**
21
+ * The containment root in force. Restored alongside the cwd so a delegated
22
+ * child can never leave the parent's sandbox wider — or narrower — than it
23
+ * found it. A child that ran `setShellRoot(undefined)` would otherwise hand the
24
+ * parent an unconfined shell for the rest of its turn.
25
+ */
26
+ shellRoot: string | undefined;
20
27
  }
21
28
 
22
29
  /** Capture the state a nested run must not leak into its parent. */
@@ -24,11 +31,15 @@ export function captureRunScope(): RunScope {
24
31
  return {
25
32
  todos: getTodos().map((t) => ({...t})),
26
33
  shellCwd: getShellCwd(),
34
+ shellRoot: getShellRoot(),
27
35
  };
28
36
  }
29
37
 
30
38
  /** Restore a scope captured by `captureRunScope`. Safe to call in a `finally`. */
31
39
  export function restoreRunScope(scope: RunScope): void {
32
40
  restoreTodos(scope.todos);
41
+ // Root first: `setShellCwd` is independent, but restoring the root clears or
42
+ // re-pins the boundary the cwd is then checked against.
43
+ setShellRoot(scope.shellRoot);
33
44
  setShellCwd(scope.shellCwd);
34
45
  }
package/src/agent/turn.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  import type {ToolDef} from '../tools/definitions.js';
24
24
  import {executeTool, registerExtensionHandlers} from '../tools/executor.js';
25
25
  import type {ToolResult} from '../tools/executor.js';
26
+ import {projectTools} from '../tools/lazy.js';
26
27
  import {clearFileRolesCache} from './file-roles.js';
27
28
  import {runWithFallback, shortModel} from './fallback.js';
28
29
  import {buildRolesPrompt, defaultPrimaryName, listPrimaries, resolvePrimary} from './roles.js';
@@ -252,13 +253,25 @@ function extensionPromptsFor(primary: {
252
253
  return prompts.join('\n\n');
253
254
  }
254
255
 
255
- /** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
256
+ /**
257
+ * Tools the turn may use, narrowed to the primary agent's set when it declares
258
+ * one, and projected to what the model should actually be told about.
259
+ *
260
+ * `getWireTools` is the lazy-schema projection: with `PAL_LAZY_TOOLS` unset it
261
+ * returns exactly `getAllTools()`, so this stays byte-for-byte the previous
262
+ * behaviour. Narrowing happens first so a primary that excludes a tool never
263
+ * pays for its stub either.
264
+ */
256
265
  export function toolsForPrimary(primaryName?: string): ToolDef[] {
257
266
  const all = getAllTools();
258
267
  const primary = primaryName ? resolvePrimary(primaryName) : null;
259
- if (!primary?.tools) return all;
260
- const allowed = new Set(primary.tools);
261
- return all.filter((t) => allowed.has(t.function.name));
268
+ const narrowed = !primary?.tools
269
+ ? all
270
+ : (() => {
271
+ const allowed = new Set(primary.tools);
272
+ return all.filter((t) => allowed.has(t.function.name));
273
+ })();
274
+ return projectTools(narrowed);
262
275
  }
263
276
 
264
277
  /**
package/src/app-config.ts CHANGED
@@ -24,6 +24,23 @@ export interface Config {
24
24
  modelRotation: boolean;
25
25
  }
26
26
 
27
+ /**
28
+ * Platform-specific shell guidance.
29
+ *
30
+ * This MUST be derived from the host, not hardcoded: the previous version
31
+ * hardcoded the Windows text, so a Linux/macOS user was told their shell was
32
+ * cmd.exe and that `ls`/`cat` did not exist. Interactive sessions never
33
+ * noticed because the model worked around it; a headless task run on Windows
34
+ * burned its whole round budget retrying POSIX commands that the prompt had
35
+ * not warned it about.
36
+ */
37
+ function shellGuidance(): string {
38
+ if (process.platform === 'win32') {
39
+ return 'Windows shell: the bash tool ALREADY runs inside cmd.exe. Write native commands directly (`dir`, `type`, `findstr`, `where`) and NEVER prefix them with `cmd /c`. Unix commands (`ls`, `cat`, `grep`, `head`, `rm`) do not exist here. Keep commands to a single line without `&&` chains when possible. Be concise; show code only when asked.';
40
+ }
41
+ return 'POSIX shell: the bash tool ALREADY runs inside /bin/sh. Write commands directly (`ls`, `cat`, `grep`, `find`, `rg`) and NEVER prefix them with `bash -c` or `sh -c`. Keep commands to a single line; prefer `&&` over separate calls only when the steps are genuinely dependent. Be concise; show code only when asked.';
42
+ }
43
+
27
44
  const DEFAULT_SYSTEM_PROMPT = [
28
45
  "pal — a terminal coding agent working in the user's project.",
29
46
  'TOOLS: Never guess about files — read them. Batch independent tool calls in one response.',
@@ -32,11 +49,22 @@ const DEFAULT_SYSTEM_PROMPT = [
32
49
  "DON'T LOOP: Never repeat a tool call with identical arguments — it cannot give a different result. If something fails twice, change approach or report the blocker.",
33
50
  'STOP: Once every todo item is done and the request is satisfied, stop calling tools and reply. Do not re-read files you already have.',
34
51
  'DELEGATE: For broad multi-file exploration, use `delegate` to keep your own context small.',
35
- 'Windows shell: the bash tool ALREADY runs inside cmd.exe. Write native commands directly (`dir`, `type`, `findstr`, `where`) and NEVER prefix them with `cmd /c`. Unix commands (`ls`, `cat`, `grep`, `head`, `rm`) do not exist here. Keep commands to a single line without `&&` chains when possible. Be concise; show code only when asked.',
52
+ 'EXPLORE: Before editing, locate the exact file and symbol. One `glob` or `grep_search`, then `read` the file — do not spend rounds listing directories.',
53
+ shellGuidance(),
36
54
  ].join('\n');
37
55
 
38
56
  const EFFORTS = ['low', 'medium', 'high'] as const;
39
57
 
58
+ /**
59
+ * Effort used when neither the env var nor `config.json` says otherwise.
60
+ *
61
+ * `high` on purpose: reasoning quality is the thing users most notice losing,
62
+ * and a silent downgrade to `medium` is worse than paying for the tokens the
63
+ * model actually needed. Override per-session with `/effort`, permanently with
64
+ * `REASONING_EFFORT` or `~/.pal/config.json`.
65
+ */
66
+ export const DEFAULT_REASONING_EFFORT = 'high' as const;
67
+
40
68
  /**
41
69
  * Extensions every install gets when `~/.pal/config.json` names none.
42
70
  *
@@ -74,12 +102,16 @@ function intEnv(name: string, fallback: number, min = 0): number {
74
102
  return n;
75
103
  }
76
104
 
77
- function effortEnv(): 'low' | 'medium' | 'high' {
105
+ /**
106
+ * `REASONING_EFFORT` from the env, or `undefined` when unset so the caller can
107
+ * fall through to config.json. An invalid value is reported and ignored.
108
+ */
109
+ function effortEnv(): 'low' | 'medium' | 'high' | undefined {
78
110
  const raw = process.env.REASONING_EFFORT;
79
- if (raw === undefined || raw === '') return 'medium';
111
+ if (raw === undefined || raw === '') return undefined;
80
112
  if ((EFFORTS as readonly string[]).includes(raw)) return raw as (typeof EFFORTS)[number];
81
- console.error(`pal: ignoring invalid REASONING_EFFORT=${JSON.stringify(raw)} — using medium`);
82
- return 'medium';
113
+ console.error(`pal: ignoring invalid REASONING_EFFORT=${JSON.stringify(raw)}`);
114
+ return undefined;
83
115
  }
84
116
 
85
117
  function strEnv(name: string, fallback: string): string {
@@ -134,6 +166,16 @@ export function loadConfig(): Config {
134
166
  // Context limit: env wins, then config.json, then the built-in default.
135
167
  const savedContextLimit = intConfig(saved.contextLimit, 'contextLimit');
136
168
 
169
+ // Effort: env wins, then config.json, then the default. Reading it back from
170
+ // config.json is what makes `/effort` survive a restart — `saveSetting` wrote
171
+ // the key but nothing ever loaded it.
172
+ const savedEffort = saved.reasoningEffort;
173
+ const reasoningEffort =
174
+ effortEnv() ??
175
+ ((EFFORTS as readonly string[]).includes(savedEffort as string)
176
+ ? (savedEffort as (typeof EFFORTS)[number])
177
+ : DEFAULT_REASONING_EFFORT);
178
+
137
179
  return {
138
180
  model: strEnv('MODEL', strEnv('PAL_MODEL', savedModel ?? 'deepseek/deepseek-chat')),
139
181
  systemPrompt: strEnv('SYSTEM_PROMPT', savedPrompt ?? DEFAULT_SYSTEM_PROMPT),
@@ -141,7 +183,7 @@ export function loadConfig(): Config {
141
183
  maxRetries: intEnv('MAX_RETRIES', 1, 0),
142
184
  retryBaseMs: intEnv('RETRY_BASE_MS', 2000, 0),
143
185
  contextLimit: intEnv('CONTEXT_LIMIT', savedContextLimit ?? 200_000, 1000),
144
- reasoningEffort: effortEnv(),
186
+ reasoningEffort,
145
187
  extensions,
146
188
  modelRotation: boolEnv('PAL_MODEL_ROTATION', boolValue(saved.modelRotation) ?? false),
147
189
  };
package/src/compaction.ts CHANGED
@@ -33,6 +33,25 @@ export function estimateMessagesTokens(messages: CompactableMessage[]): number {
33
33
  }, 0);
34
34
  }
35
35
 
36
+ /**
37
+ * The fixed per-request overhead the model is charged on *every* call: the
38
+ * composed system prompt plus the tool schemas.
39
+ *
40
+ * The context gauge used to count only `config.systemPrompt` — but
41
+ * `composeSystemPrompt()` appends the primary preamble, the role table, the
42
+ * skill listing and extension guidance, and the tool schemas (~2k tokens, 93%
43
+ * of the fixed cost) were never counted at all. That made the reported context
44
+ * fill materially optimistic, especially early in a conversation where the
45
+ * fixed overhead dominates.
46
+ *
47
+ * `toolTokens` is passed in rather than imported to keep this module free of a
48
+ * dependency on the tool registry (which would make the cycle
49
+ * compaction → definitions → compaction).
50
+ */
51
+ export function fixedPromptTokens(systemPrompt: string, toolTokens = 0): number {
52
+ return estimateTokens(systemPrompt) + toolTokens;
53
+ }
54
+
36
55
  export interface CompactionConfig {
37
56
  maxTokens: number;
38
57
  reservedTokens: number;
package/src/config.ts CHANGED
@@ -10,6 +10,7 @@ import {readFileSync, statSync} from 'fs';
10
10
  import {resolve, relative, isAbsolute, basename} from 'path';
11
11
  import {minimatch} from 'minimatch';
12
12
  import {TOOL_NAME_ALIASES} from './tools/definitions.js';
13
+ import type {ChildProviderConfig} from './agent/run.js';
13
14
 
14
15
  /** Config file schema. */
15
16
  export interface ToolConfig {
@@ -41,7 +42,7 @@ export interface ToolConfig {
41
42
  name: string,
42
43
  args: string,
43
44
  id: string,
44
- providerConfig: unknown,
45
+ providerConfig: ChildProviderConfig,
45
46
  signal?: AbortSignal,
46
47
  ) => Promise<{content: string; error?: boolean}>;
47
48
  };
@@ -9,6 +9,8 @@
9
9
 
10
10
  import {extname, relative, resolve} from 'path';
11
11
  import {log} from './logger.js';
12
+ import {runLspChecks} from './lsp/client.js';
13
+ import {isLspEnabled, serverForBatch} from './lsp/servers.js';
12
14
  import type {DiagnosticError} from './diagnostics.js';
13
15
 
14
16
  const BIOME_EXTS = new Set([
@@ -38,6 +40,23 @@ export async function runChecks(
38
40
  // tests exercise the flow through an injected checker instead.
39
41
  if (process.env.NODE_ENV === 'test') return null;
40
42
 
43
+ // LSP first, but only opt-in and only when a server actually claims these
44
+ // files. A `null` answer means "no opinion" and falls through to biome/tsc,
45
+ // so enabling PAL_LSP can never make diagnostics *worse* than they are today —
46
+ // it can only add coverage for files biome and tsc do not understand.
47
+ if (isLspEnabled()) {
48
+ const batch = serverForBatch(files);
49
+ if (batch !== null) {
50
+ const lsp = await runLspChecks({
51
+ spec: batch.spec,
52
+ files: batch.covered,
53
+ cwd: ctx.cwd,
54
+ budgetMs: ctx.budgetMs,
55
+ });
56
+ if (lsp !== null) return lsp;
57
+ }
58
+ }
59
+
41
60
  const biomeFiles = files.filter((f) => BIOME_EXTS.has(extname(f).toLowerCase()));
42
61
  const needsTsc = files.some((f) => TS_EXTS.has(extname(f).toLowerCase()));
43
62
  if (biomeFiles.length === 0 && !needsTsc) return null;
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@ export type {
6
6
  StreamEvent,
7
7
  ModelRoute,
8
8
  } from './provider/types.js';
9
- export {createOpenRouterProvider} from './provider/openrouter.js';
9
+ export {createOpenRouterProvider, resetProviderSession} from './provider/openrouter.js';
10
10
  export {
11
11
  resolveAuth,
12
12
  resolveAllKeys,
@@ -33,7 +33,6 @@ export type {ProviderDef} from './provider/registry.js';
33
33
  export {
34
34
  runAgent,
35
35
  summarizeArgs,
36
- getEffortParams,
37
36
  buildApiMessages,
38
37
  sanitizeWireMessages,
39
38
  rollbackTurn,
@@ -121,7 +120,12 @@ export {createSharedState} from './runtime/state.js';
121
120
  export type {SharedState, BackgroundAgent, TodoItem} from './runtime/state.js';
122
121
 
123
122
  // Config
124
- export {loadConfig, loadPermissions, clearPermissionsCache} from './app-config.js';
123
+ export {
124
+ loadConfig,
125
+ loadPermissions,
126
+ clearPermissionsCache,
127
+ DEFAULT_REASONING_EFFORT,
128
+ } from './app-config.js';
125
129
  export type {Config} from './app-config.js';
126
130
  export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
127
131
  export {
@@ -139,16 +143,33 @@ export {
139
143
  CORE_TOOLS,
140
144
  TOOL_NAME_ALIASES,
141
145
  getAllTools,
146
+ getWireTools,
147
+ estimateToolSchemaTokens,
142
148
  registerExtensionTools,
143
149
  validateRequiredArgs,
144
150
  clearExtensionTools,
145
151
  getExtensionTools,
146
152
  } from './tools/definitions.js';
147
153
  export type {ToolDef} from './tools/definitions.js';
154
+ export {
155
+ isLazyToolsEnabled,
156
+ isDeferred,
157
+ deferrableTools,
158
+ projectTools,
159
+ expandTools,
160
+ resetExpanded,
161
+ expandedTools,
162
+ DEFAULT_DEFERRABLE,
163
+ LAZY_ENV,
164
+ } from './tools/lazy.js';
148
165
  export {
149
166
  executeTool,
150
167
  registerExtensionHandlers,
151
168
  resetShell,
169
+ getShellCwd,
170
+ setShellCwd,
171
+ getShellRoot,
172
+ setShellRoot,
152
173
  isMutatingToolset,
153
174
  registerMutatingTools,
154
175
  registerHistoryProvider,
@@ -203,6 +224,7 @@ export {
203
224
  compactMessages,
204
225
  shouldCompact,
205
226
  estimateMessagesTokens,
227
+ fixedPromptTokens,
206
228
  buildModelView,
207
229
  summarizeRange,
208
230
  compactionBoundary,
@@ -214,6 +236,10 @@ export {complete} from './provider/complete.js';
214
236
  export type {CompleteOptions, CompleteResult} from './provider/complete.js';
215
237
  export {pickCheapModel} from './provider/pick-model.js';
216
238
 
239
+ // Reasoning effort → wire shape (protocol-aware)
240
+ export {getEffortParams, isReasoningModel} from './provider/effort.js';
241
+ export type {Effort, WireProtocol} from './provider/effort.js';
242
+
217
243
  // Model pricing / cost resolution
218
244
  export {
219
245
  estimateCost,