pal-code 0.0.7 → 0.0.10

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 (61) 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 +11 -11
  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 +8 -10
  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 +14 -9
  17. package/packages/cli/src/utils/permissions.ts +3 -3
  18. package/packages/cli/src/utils/format.test.ts +0 -167
  19. package/packages/core/src/agent/events.ts +0 -36
  20. package/packages/core/src/agent/fallback.test.ts +0 -99
  21. package/packages/core/src/agent/fallback.ts +0 -344
  22. package/packages/core/src/agent/index.ts +0 -35
  23. package/packages/core/src/agent/protocol.test.ts +0 -136
  24. package/packages/core/src/agent/resume-compaction.test.ts +0 -116
  25. package/packages/core/src/agent/roles.ts +0 -188
  26. package/packages/core/src/agent/run.test.ts +0 -207
  27. package/packages/core/src/agent/run.ts +0 -713
  28. package/packages/core/src/agent/scope.ts +0 -34
  29. package/packages/core/src/agent/todos.ts +0 -66
  30. package/packages/core/src/compaction.protocol.test.ts +0 -90
  31. package/packages/core/src/compaction.test.ts +0 -101
  32. package/packages/core/src/compaction.ts +0 -243
  33. package/packages/core/src/config.test.ts +0 -40
  34. package/packages/core/src/config.ts +0 -387
  35. package/packages/core/src/extensions.ts +0 -178
  36. package/packages/core/src/index.ts +0 -157
  37. package/packages/core/src/logger.ts +0 -54
  38. package/packages/core/src/provider/auth.ts +0 -153
  39. package/packages/core/src/provider/complete.ts +0 -63
  40. package/packages/core/src/provider/index.ts +0 -6
  41. package/packages/core/src/provider/openrouter.test.ts +0 -59
  42. package/packages/core/src/provider/openrouter.ts +0 -304
  43. package/packages/core/src/provider/pick-model.ts +0 -43
  44. package/packages/core/src/provider/registry.ts +0 -222
  45. package/packages/core/src/provider/types.ts +0 -61
  46. package/packages/core/src/repo-map.ts +0 -177
  47. package/packages/core/src/session/index.ts +0 -2
  48. package/packages/core/src/session/migration.test.ts +0 -104
  49. package/packages/core/src/session/store-v2-repair.test.ts +0 -209
  50. package/packages/core/src/session/store.test.ts +0 -235
  51. package/packages/core/src/session/store.ts +0 -677
  52. package/packages/core/src/session/types.ts +0 -72
  53. package/packages/core/src/snapshots.ts +0 -107
  54. package/packages/core/src/tools/definitions.ts +0 -365
  55. package/packages/core/src/tools/executor.test.ts +0 -122
  56. package/packages/core/src/tools/executor.ts +0 -1363
  57. package/packages/core/src/tools/index.ts +0 -5
  58. package/packages/core/src/tools/search.ts +0 -201
  59. package/scripts/postinstall.js +0 -121
  60. package/scripts/preinstall.js +0 -51
  61. package/scripts/sync-version.js +0 -35
@@ -1,157 +0,0 @@
1
- // Provider abstraction (preferred)
2
- export type {Provider, ProviderConfig, ProviderModel, StreamEvent} from './provider/types.js';
3
- export {createOpenRouterProvider} from './provider/openrouter.js';
4
- export {
5
- resolveAuth,
6
- resolveAllKeys,
7
- hasAnyKey,
8
- saveKey,
9
- removeKey,
10
- configPath,
11
- readPalConfig,
12
- saveSetting,
13
- } from './provider/auth.js';
14
- export type {ResolvedAuth, ProviderKeys} from './provider/auth.js';
15
- export {
16
- PROVIDERS,
17
- getProvider,
18
- detectProvider,
19
- providerForModel,
20
- loadCustomProviders,
21
- } from './provider/registry.js';
22
- export type {ProviderDef} from './provider/registry.js';
23
-
24
- // Agent
25
- export {
26
- runAgent,
27
- summarizeArgs,
28
- getEffortParams,
29
- buildApiMessages,
30
- sanitizeWireMessages,
31
- rollbackTurn,
32
- seqToCount,
33
- } from './agent/run.js';
34
- export {
35
- runWithFallback,
36
- resolveModelIds,
37
- fetchProviderModels,
38
- clearModelCache,
39
- createProviderFor,
40
- providerAccessible,
41
- shortModel,
42
- isRetryableError,
43
- isQuotaExhausted,
44
- isRateLimited,
45
- } from './agent/fallback.js';
46
- export type {RunWithFallbackOptions} from './agent/fallback.js';
47
- export type {
48
- AgentRunEvent,
49
- RunAgentOptions,
50
- RunAgentUsage,
51
- ConversationMessage,
52
- UserMsg,
53
- AssistantMsg,
54
- ToolResultMsg,
55
- } from './agent/run.js';
56
- export {onAgentEvent, emitAgentEvent} from './agent/events.js';
57
- export type {AgentEvent as AgentLifecycleEvent} from './agent/events.js';
58
- export {
59
- setTodos,
60
- getTodos,
61
- clearTodos,
62
- formatTodos,
63
- snapshotTodos,
64
- restoreTodos,
65
- } from './agent/todos.js';
66
- export type {Todo, TodoStatus} from './agent/todos.js';
67
- export {captureRunScope, restoreRunScope} from './agent/scope.js';
68
- export type {RunScope} from './agent/scope.js';
69
- export {
70
- registerRoleProvider,
71
- clearRoleProvider,
72
- resolveRoleSpec,
73
- listRoleSpecs,
74
- getMaxParallel,
75
- DEFAULT_MAX_PARALLEL,
76
- listPrimaries,
77
- defaultPrimaryName,
78
- resolvePrimary,
79
- hasRoleProvider,
80
- buildRolesPrompt,
81
- } from './agent/roles.js';
82
- export type {RoleSpec, RoleKind, RoleProvider, PrimarySpec} from './agent/roles.js';
83
-
84
- // Config
85
- export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
86
- export {
87
- loadPermissionConfig,
88
- checkPermission,
89
- detectDangerousBash,
90
- BUILTIN_SENSITIVE_RULES,
91
- BUILTIN_PERMISSION_DEFAULTS,
92
- DANGEROUS_BASH_PATTERNS,
93
- } from './config.js';
94
- export type {ToolConfig, PermissionConfig, PermissionRule} from './config.js';
95
-
96
- // Tools
97
- export {
98
- CORE_TOOLS,
99
- getAllTools,
100
- registerExtensionTools,
101
- getExtensionTools,
102
- } from './tools/definitions.js';
103
- export type {ToolDef} from './tools/definitions.js';
104
- export {
105
- executeTool,
106
- registerExtensionHandlers,
107
- resetShell,
108
- isMutatingToolset,
109
- registerMutatingTools,
110
- registerHistoryProvider,
111
- } from './tools/executor.js';
112
- export type {ToolResult, RecallableRow} from './tools/executor.js';
113
-
114
- // Extensions
115
- export {loadExtensions, defaultExtensionRoots} from './extensions.js';
116
- export type {
117
- ToolExtension,
118
- ToolHandler,
119
- LoadedExtensions,
120
- LoadExtensionsOptions,
121
- } from './extensions.js';
122
-
123
- // Repo Map
124
- export {buildRepoMap} from './repo-map.js';
125
-
126
- // Session
127
- export {SessionStore, deriveMessageMeta} from './session/store.js';
128
- export type {
129
- Session,
130
- SessionTokenomics,
131
- StoredMessage,
132
- MessageMeta,
133
- CompactionRecord,
134
- } from './session/types.js';
135
-
136
- // Compaction
137
- export {
138
- compactMessages,
139
- shouldCompact,
140
- estimateMessagesTokens,
141
- buildModelView,
142
- summarizeRange,
143
- compactionBoundary,
144
- } from './compaction.js';
145
- export type {CompactionConfig, ModelView, Summarizer} from './compaction.js';
146
-
147
- // Provider completion helper
148
- export {complete} from './provider/complete.js';
149
- export type {CompleteOptions, CompleteResult} from './provider/complete.js';
150
- export {pickCheapModel} from './provider/pick-model.js';
151
-
152
- // Debug logging
153
- export {log, isDebugEnabled} from './logger.js';
154
-
155
- // File snapshots (undo)
156
- export {snapshotFile, listSnapshots, restoreSnapshot} from './snapshots.js';
157
- export type {Snapshot} from './snapshots.js';
@@ -1,54 +0,0 @@
1
- /**
2
- * Debug logger — enabled with PAL_DEBUG=1.
3
- * Appends to ~/.pal/logs/pal-YYYY-MM-DD.log, redacting API keys.
4
- * Never throws into the agent loop.
5
- */
6
-
7
- import {appendFileSync, mkdirSync} from 'fs';
8
- import {join} from 'path';
9
-
10
- function home(): string {
11
- return process.env.USERPROFILE ?? process.env.HOME ?? '.';
12
- }
13
-
14
- let _logPath: string | null = null;
15
-
16
- function logPath(): string {
17
- if (!_logPath) {
18
- const dir = join(home(), '.pal', 'logs');
19
- try {
20
- mkdirSync(dir, {recursive: true});
21
- } catch {
22
- /* ignore */
23
- }
24
- const date = new Date().toISOString().slice(0, 10);
25
- _logPath = join(dir, `pal-${date}.log`);
26
- }
27
- return _logPath;
28
- }
29
-
30
- export function isDebugEnabled(): boolean {
31
- const v = process.env.PAL_DEBUG;
32
- return v === '1' || v === 'true';
33
- }
34
-
35
- const SECRET_RE =
36
- /(sk-[A-Za-z0-9_-]{6,}|AIza[A-Za-z0-9_-]{6,}|AQ\.[A-Za-z0-9_-]{6,}|gsk_[A-Za-z0-9_-]{6,}|xai-[A-Za-z0-9_-]{6,})/g;
37
-
38
- function redact(text: string): string {
39
- return text.replace(SECRET_RE, '***REDACTED***');
40
- }
41
-
42
- export function log(section: string, data?: unknown): void {
43
- if (!isDebugEnabled()) return;
44
- try {
45
- const ts = new Date().toISOString();
46
- let body = '';
47
- if (data !== undefined) {
48
- body = ' ' + (typeof data === 'string' ? data : JSON.stringify(data, null, 2));
49
- }
50
- appendFileSync(logPath(), `[${ts}] [${section}]${redact(body)}\n`, 'utf-8');
51
- } catch {
52
- /* logging must never break the agent */
53
- }
54
- }
@@ -1,153 +0,0 @@
1
- /**
2
- * Auth resolution — BYOK (Bring Your Own Key).
3
- *
4
- * pal requires the user to supply their own API key. Keys are resolved from:
5
- * 1. Environment variables (e.g. DEEPSEEK_API_KEY, GEMINI_API_KEY)
6
- * 2. pal's own config file: ~/.pal/config.json → { "keys": { "<provider>": "<key>" } }
7
- *
8
- * No keys are read from other applications, and there is no anonymous fallback:
9
- * if nothing is configured, the caller is expected to run the setup wizard.
10
- */
11
-
12
- import {readFileSync, writeFileSync, existsSync, mkdirSync} from 'fs';
13
- import {join, dirname} from 'path';
14
- import {PROVIDERS, getProvider, detectProvider, type ProviderDef} from './registry.js';
15
-
16
- export interface ResolvedAuth {
17
- apiKey: string;
18
- source: string;
19
- provider: string;
20
- configured: boolean;
21
- }
22
-
23
- /** Map of providerId → API key. */
24
- export type ProviderKeys = Record<string, string>;
25
-
26
- const home = () => process.env.USERPROFILE ?? process.env.HOME ?? '';
27
-
28
- export function configPath(): string {
29
- return join(home(), '.pal', 'config.json');
30
- }
31
-
32
- function readConfig(): Record<string, unknown> {
33
- try {
34
- const p = configPath();
35
- if (!existsSync(p)) return {};
36
- return JSON.parse(readFileSync(p, 'utf-8')) as Record<string, unknown>;
37
- } catch {
38
- return {};
39
- }
40
- }
41
-
42
- /**
43
- * Resolve every configured provider key.
44
- * Env vars take precedence over the stored config file.
45
- */
46
- export function resolveAllKeys(): ProviderKeys {
47
- const keys: ProviderKeys = {};
48
- const cfg = readConfig();
49
- const stored = (cfg.keys ?? {}) as Record<string, string>;
50
-
51
- for (const p of PROVIDERS) {
52
- const fromEnv = process.env[p.envVar];
53
- if (fromEnv) {
54
- keys[p.id] = fromEnv;
55
- continue;
56
- }
57
- if (stored[p.id]) {
58
- keys[p.id] = stored[p.id];
59
- continue;
60
- }
61
- // Legacy flat fields from earlier pal versions
62
- if (p.id === 'gemini' && typeof cfg.geminiApiKey === 'string' && cfg.geminiApiKey) {
63
- keys.gemini = cfg.geminiApiKey;
64
- } else if (p.id === 'openrouter' && typeof cfg.apiKey === 'string' && cfg.apiKey) {
65
- keys.openrouter = cfg.apiKey;
66
- }
67
- }
68
-
69
- return keys;
70
- }
71
-
72
- /** True when at least one usable key exists, or a keyless provider was opted into. */
73
- export function hasAnyKey(keys: ProviderKeys = resolveAllKeys()): boolean {
74
- if (Object.keys(keys).length > 0) return true;
75
- const cfg = readConfig();
76
- const keyless = typeof cfg.keyless === 'string' ? cfg.keyless : null;
77
- return keyless !== null && PROVIDERS.some((p) => p.id === keyless && p.keyOptional === true);
78
- }
79
-
80
- /**
81
- * Resolve a single key. Used by callers that need one provider up-front.
82
- * When nothing is configured, returns configured=false so the caller can run setup.
83
- */
84
- export function resolveAuth(explicitKey?: string): ResolvedAuth {
85
- if (explicitKey) {
86
- const def = detectProvider(explicitKey);
87
- return {
88
- apiKey: explicitKey,
89
- source: 'explicit',
90
- provider: def?.id ?? 'unknown',
91
- configured: true,
92
- };
93
- }
94
-
95
- const keys = resolveAllKeys();
96
- // Prefer the order providers are declared in the registry.
97
- for (const p of PROVIDERS) {
98
- if (keys[p.id]) {
99
- return {apiKey: keys[p.id], source: `config:${p.id}`, provider: p.id, configured: true};
100
- }
101
- }
102
-
103
- // Keyless providers work without a key when explicitly opted into via setup.
104
- const cfg = readConfig();
105
- if (typeof cfg.keyless === 'string') {
106
- const def = getProvider(cfg.keyless);
107
- if (def?.keyOptional) {
108
- return {apiKey: 'public', source: 'keyless', provider: def.id, configured: true};
109
- }
110
- }
111
-
112
- return {apiKey: '', source: 'none', provider: 'none', configured: false};
113
- }
114
-
115
- /** Read pal's config file. */
116
- export function readPalConfig(): Record<string, unknown> {
117
- return readConfig();
118
- }
119
-
120
- /** Write a top-level setting (e.g. "model") into ~/.pal/config.json. */
121
- export function saveSetting(key: string, value: unknown): void {
122
- const cfg = readConfig();
123
- cfg[key] = value;
124
- const p = configPath();
125
- mkdirSync(dirname(p), {recursive: true});
126
- writeFileSync(p, JSON.stringify(cfg, null, 2), 'utf-8');
127
- }
128
-
129
- /** Persist a key into ~/.pal/config.json (merging with existing entries). */
130
- export function saveKey(providerId: string, apiKey: string): void {
131
- const cfg = readConfig();
132
- const keys = {...((cfg.keys ?? {}) as Record<string, string>)};
133
- keys[providerId] = apiKey;
134
- cfg.keys = keys;
135
-
136
- const p = configPath();
137
- mkdirSync(dirname(p), {recursive: true});
138
- writeFileSync(p, JSON.stringify(cfg, null, 2), 'utf-8');
139
- }
140
-
141
- /** Remove a stored key. */
142
- export function removeKey(providerId: string): void {
143
- const cfg = readConfig();
144
- const keys = {...((cfg.keys ?? {}) as Record<string, string>)};
145
- delete keys[providerId];
146
- cfg.keys = keys;
147
-
148
- const p = configPath();
149
- mkdirSync(dirname(p), {recursive: true});
150
- writeFileSync(p, JSON.stringify(cfg, null, 2), 'utf-8');
151
- }
152
-
153
- export type {ProviderDef};
@@ -1,63 +0,0 @@
1
- /**
2
- * Non-streaming convenience wrapper over `Provider.stream()`.
3
- *
4
- * The Provider interface only exposes a streaming method, but title generation
5
- * and context summarization need a plain "give me the whole answer" call. This
6
- * accumulates the text deltas and resolves once the stream finishes, so callers
7
- * don't have to reimplement the loop (and its error handling) each time.
8
- */
9
-
10
- import type {Provider} from './types.js';
11
-
12
- export interface CompleteOptions {
13
- model: string;
14
- messages: Array<Record<string, unknown>>;
15
- signal?: AbortSignal;
16
- /**
17
- * Extra params merged into the stream call (e.g. reasoning-effort knobs).
18
- * Title/summary callers deliberately pass none.
19
- */
20
- params?: Record<string, unknown>;
21
- }
22
-
23
- export interface CompleteResult {
24
- text: string;
25
- usage?: {promptTokens: number; completionTokens: number; cachedTokens?: number};
26
- }
27
-
28
- /**
29
- * Run a completion to finish and return the concatenated text.
30
- *
31
- * Guarantees:
32
- * - Throws on an `error` stream event (so callers can fall back).
33
- * - Tolerates providers that emit text without a trailing `done` event.
34
- */
35
- export async function complete(
36
- provider: Provider,
37
- opts: CompleteOptions,
38
- ): Promise<CompleteResult> {
39
- let text = '';
40
- let usage: CompleteResult['usage'];
41
-
42
- for await (const event of provider.stream({
43
- model: opts.model,
44
- messages: opts.messages,
45
- tools: [],
46
- signal: opts.signal,
47
- ...(opts.params ?? {}),
48
- } as never)) {
49
- if (event.type === 'text' && event.content) {
50
- text += event.content;
51
- } else if (event.type === 'error') {
52
- throw new Error(event.content ?? 'provider returned an error event');
53
- } else if (event.type === 'done' && event.usage) {
54
- usage = {
55
- promptTokens: event.usage.promptTokens ?? 0,
56
- completionTokens: event.usage.completionTokens ?? 0,
57
- cachedTokens: event.usage.cachedTokens,
58
- };
59
- }
60
- }
61
-
62
- return {text: text.trim(), usage};
63
- }
@@ -1,6 +0,0 @@
1
- export type {Provider, ProviderConfig, ProviderModel, StreamEvent} from './types.js';
2
- export {createOpenRouterProvider} from './openrouter.js';
3
- export {resolveAuth} from './auth.js';
4
- export {complete} from './complete.js';
5
- export type {CompleteOptions, CompleteResult} from './complete.js';
6
- export {pickCheapModel} from './pick-model.js';
@@ -1,59 +0,0 @@
1
- import {test, expect, afterEach} from 'bun:test';
2
- import {createOpenRouterProvider} from './openrouter.js';
3
-
4
- const originalFetch = globalThis.fetch;
5
-
6
- afterEach(() => {
7
- globalThis.fetch = originalFetch;
8
- });
9
-
10
- function sseResponse(chunks: string[]): Response {
11
- const encoder = new TextEncoder();
12
- const stream = new ReadableStream<Uint8Array>({
13
- start(controller) {
14
- for (const chunk of chunks) {
15
- controller.enqueue(encoder.encode(chunk));
16
- }
17
- controller.close();
18
- },
19
- });
20
- return new Response(stream, {status: 200});
21
- }
22
-
23
- test('OpenRouterProvider: accumulates fragmented tool calls into one tool_use event', async () => {
24
- globalThis.fetch = (async () =>
25
- sseResponse([
26
- 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":""}}]},"finish_reason":null}]}\n\n',
27
- 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"path\\":\\"a.ts\\"}"}}]},"finish_reason":null}]}\n\n',
28
- 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}\n\n',
29
- 'data: {"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":2,"total_tokens":12}}\n\n',
30
- 'data: [DONE]\n\n',
31
- ])) as unknown as typeof fetch;
32
-
33
- const provider = createOpenRouterProvider({
34
- id: 'test',
35
- baseUrl: 'https://example.com/v1',
36
- apiKey: 'sk-test',
37
- });
38
- await provider.init();
39
-
40
- const events = [];
41
- for await (const event of provider.stream({
42
- model: 'test-model',
43
- messages: [{role: 'user', content: 'hi'}],
44
- tools: [],
45
- })) {
46
- events.push(event);
47
- }
48
-
49
- const toolUses = events.filter((e) => e.type === 'tool_use');
50
- expect(toolUses).toHaveLength(1);
51
- expect(toolUses[0]?.toolCall).toEqual({
52
- id: 'call_1',
53
- name: 'read_file',
54
- arguments: '{"path":"a.ts"}',
55
- });
56
-
57
- const done = events.find((e) => e.type === 'done');
58
- expect(done?.usage?.promptTokens).toBe(10);
59
- });