pal-code 0.0.5

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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -0
  3. package/SYSTEM.md +146 -0
  4. package/bin/pal-code.js +131 -0
  5. package/package.json +68 -0
  6. package/packages/cli/README.md +77 -0
  7. package/packages/cli/src/agent-panel.ts +94 -0
  8. package/packages/cli/src/commands/ext.ts +79 -0
  9. package/packages/cli/src/commands/mcp-registry.ts +136 -0
  10. package/packages/cli/src/commands/mcp.ts +186 -0
  11. package/packages/cli/src/commands.ts +153 -0
  12. package/packages/cli/src/components/message-box.ts +35 -0
  13. package/packages/cli/src/components/permission-prompt.ts +185 -0
  14. package/packages/cli/src/components/render-history.ts +143 -0
  15. package/packages/cli/src/components/run-view.ts +256 -0
  16. package/packages/cli/src/components/sidebar.ts +120 -0
  17. package/packages/cli/src/components/status-line.ts +26 -0
  18. package/packages/cli/src/config.ts +107 -0
  19. package/packages/cli/src/index.ts +1606 -0
  20. package/packages/cli/src/overlays/key-input.ts +167 -0
  21. package/packages/cli/src/overlays/model-picker.ts +106 -0
  22. package/packages/cli/src/overlays/session-picker.ts +168 -0
  23. package/packages/cli/src/overlays/wizard.ts +145 -0
  24. package/packages/cli/src/state.ts +133 -0
  25. package/packages/cli/src/theme.ts +88 -0
  26. package/packages/cli/src/turn.ts +266 -0
  27. package/packages/cli/src/utils/cost.ts +111 -0
  28. package/packages/cli/src/utils/format.test.ts +167 -0
  29. package/packages/cli/src/utils/format.ts +248 -0
  30. package/packages/cli/src/utils/highlight.ts +358 -0
  31. package/packages/cli/src/utils/permissions.ts +196 -0
  32. package/packages/core/src/agent/events.ts +36 -0
  33. package/packages/core/src/agent/fallback.test.ts +99 -0
  34. package/packages/core/src/agent/fallback.ts +344 -0
  35. package/packages/core/src/agent/index.ts +35 -0
  36. package/packages/core/src/agent/protocol.test.ts +136 -0
  37. package/packages/core/src/agent/resume-compaction.test.ts +116 -0
  38. package/packages/core/src/agent/roles.ts +188 -0
  39. package/packages/core/src/agent/run.test.ts +207 -0
  40. package/packages/core/src/agent/run.ts +713 -0
  41. package/packages/core/src/agent/scope.ts +34 -0
  42. package/packages/core/src/agent/todos.ts +66 -0
  43. package/packages/core/src/compaction.protocol.test.ts +90 -0
  44. package/packages/core/src/compaction.test.ts +101 -0
  45. package/packages/core/src/compaction.ts +243 -0
  46. package/packages/core/src/config.test.ts +40 -0
  47. package/packages/core/src/config.ts +387 -0
  48. package/packages/core/src/extensions.ts +178 -0
  49. package/packages/core/src/index.ts +157 -0
  50. package/packages/core/src/logger.ts +54 -0
  51. package/packages/core/src/provider/auth.ts +153 -0
  52. package/packages/core/src/provider/complete.ts +63 -0
  53. package/packages/core/src/provider/index.ts +6 -0
  54. package/packages/core/src/provider/openrouter.test.ts +59 -0
  55. package/packages/core/src/provider/openrouter.ts +304 -0
  56. package/packages/core/src/provider/pick-model.ts +43 -0
  57. package/packages/core/src/provider/registry.ts +222 -0
  58. package/packages/core/src/provider/types.ts +61 -0
  59. package/packages/core/src/repo-map.ts +177 -0
  60. package/packages/core/src/session/index.ts +2 -0
  61. package/packages/core/src/session/migration.test.ts +104 -0
  62. package/packages/core/src/session/store-v2-repair.test.ts +209 -0
  63. package/packages/core/src/session/store.test.ts +235 -0
  64. package/packages/core/src/session/store.ts +677 -0
  65. package/packages/core/src/session/types.ts +72 -0
  66. package/packages/core/src/snapshots.ts +107 -0
  67. package/packages/core/src/tools/definitions.ts +365 -0
  68. package/packages/core/src/tools/executor.test.ts +122 -0
  69. package/packages/core/src/tools/executor.ts +1363 -0
  70. package/packages/core/src/tools/index.ts +5 -0
  71. package/packages/core/src/tools/search.ts +201 -0
  72. package/scripts/postinstall.js +121 -0
  73. package/scripts/preinstall.js +51 -0
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Role registry — the seam between core's `delegate` tool and the orchestration
3
+ * extension (`@pal/agents`).
4
+ *
5
+ * Core must not import `.pal`-adjacent extension config, and extensions must not
6
+ * be required for delegation to work. So core defines the *shape* of a role and
7
+ * a registry; the extension populates it at load time. If no extension registers
8
+ * one, `resolveRoleSpec` returns null and `delegate` falls back to its original
9
+ * ad-hoc behaviour.
10
+ *
11
+ * Two axes, mirroring OMO:
12
+ * - `agent` — curated read-only specialist (explore, librarian, …)
13
+ * - `category` — implementation lane (build, deep, quick, architect, …)
14
+ */
15
+
16
+ export type RoleKind = 'agent' | 'category';
17
+
18
+ /** A named specialist an agent turn can delegate to. */
19
+ export interface RoleSpec {
20
+ /** Role name, e.g. 'explore' or 'build'. */
21
+ name: string;
22
+ /** Which axis this role belongs to. */
23
+ kind: RoleKind;
24
+ /** One-line description shown to the model in the system prompt. */
25
+ description: string;
26
+ /** `provider/model` spec. When omitted, the parent's session model is used. */
27
+ model?: string;
28
+ /** Reasoning effort forwarded to the provider. Default: 'medium'. */
29
+ reasoning?: 'low' | 'medium' | 'high';
30
+ /** Tool names this role may use. Absent means "use the safe default". */
31
+ tools?: string[];
32
+ /** Max tool-call rounds for the child. */
33
+ maxRounds: number;
34
+ /** System prompt for the child agent. */
35
+ systemPrompt: string;
36
+ }
37
+
38
+ export interface RoleProvider {
39
+ /** Resolve one role by name, or null if unknown. */
40
+ resolve: (name: string, kind: RoleKind) => RoleSpec | null;
41
+ /** All roles currently available, for prompt injection + the /roles command. */
42
+ list: () => RoleSpec[];
43
+ /** Concurrency cap for `delegate_parallel`. Defaults to 3 when omitted. */
44
+ maxParallel?: () => number;
45
+ /** Primary agents the user can Tab between. Omitted → none. */
46
+ listPrimary?: () => PrimarySpec[];
47
+ /** Name of the primary agent selected on startup. Omitted → first primary. */
48
+ defaultPrimary?: () => string;
49
+ }
50
+
51
+ /**
52
+ * A **primary agent** — an agent the *user* talks to, selected with Tab.
53
+ *
54
+ * This is the OpenCode/OMO concept: the primary owns the conversation turn.
55
+ * It is deliberately distinct from a `RoleSpec`, which is a *delegation target*
56
+ * the main agent fans work out to. Confusing the two is the bug this module
57
+ * exists to prevent.
58
+ */
59
+ export interface PrimarySpec {
60
+ /** Stable id, e.g. 'pal' or 'plan'. */
61
+ name: string;
62
+ /** One-line description for the /help listing. */
63
+ description: string;
64
+ /** Short label shown in the input indicator. Defaults to `name`. */
65
+ label?: string;
66
+ /** Theme colour key (e.g. 'cyan', 'red'). Defaults to 'cyan'. */
67
+ color?: string;
68
+ /**
69
+ * When set, the main agent is restricted to these tools for the turn —
70
+ * this is how a read-only "plan" primary is enforced rather than merely
71
+ * requested in the prompt.
72
+ */
73
+ tools?: string[];
74
+ /** Extra system-prompt guidance prepended to the base prompt. */
75
+ systemPrompt?: string;
76
+ /**
77
+ * Which side of the plan/execute handoff this primary serves.
78
+ *
79
+ * When set, it is authoritative — the front-end uses it instead of inferring
80
+ * from `tools`, so a config typo can't silently swap the two roles.
81
+ */
82
+ role?: 'plan' | 'orchestrator';
83
+ }
84
+
85
+ /** Fallback concurrency when no extension registers one. */
86
+ export const DEFAULT_MAX_PARALLEL = 3;
87
+
88
+ let _provider: RoleProvider | null = null;
89
+
90
+ /**
91
+ * Register the role provider. Called by the orchestration extension's setup
92
+ * hook. A later registration replaces the previous one (so `/reload` works).
93
+ */
94
+ export function registerRoleProvider(provider: RoleProvider): void {
95
+ _provider = provider;
96
+ }
97
+
98
+ /** Unregister the role provider (used by `/reload` and tests). */
99
+ export function clearRoleProvider(): void {
100
+ _provider = null;
101
+ }
102
+
103
+ /** Resolve a role by name and axis. Returns null when no provider is registered. */
104
+ export function resolveRoleSpec(name: string, kind: RoleKind): RoleSpec | null {
105
+ return _provider?.resolve(name, kind) ?? null;
106
+ }
107
+
108
+ /** All roles, or an empty array when no provider is registered. */
109
+ export function listRoleSpecs(): RoleSpec[] {
110
+ return _provider?.list() ?? [];
111
+ }
112
+
113
+ /** Concurrency cap for `delegate_parallel`. */
114
+ export function getMaxParallel(): number {
115
+ try {
116
+ return _provider?.maxParallel?.() ?? DEFAULT_MAX_PARALLEL;
117
+ } catch {
118
+ return DEFAULT_MAX_PARALLEL;
119
+ }
120
+ }
121
+
122
+ /** Primary agents the user can Tab between (empty when none are registered). */
123
+ export function listPrimaries(): PrimarySpec[] {
124
+ try {
125
+ return _provider?.listPrimary?.() ?? [];
126
+ } catch {
127
+ return [];
128
+ }
129
+ }
130
+
131
+ /** Name of the primary agent to select on startup. */
132
+ export function defaultPrimaryName(): string {
133
+ const primaries = listPrimaries();
134
+ if (primaries.length === 0) return 'pal';
135
+ try {
136
+ const name = _provider?.defaultPrimary?.();
137
+ if (name && primaries.some((p) => p.name === name)) return name;
138
+ } catch {
139
+ /* fall through */
140
+ }
141
+ return primaries[0].name;
142
+ }
143
+
144
+ /** Resolve one primary agent by name, or null if unknown. */
145
+ export function resolvePrimary(name: string): PrimarySpec | null {
146
+ return listPrimaries().find((p) => p.name === name) ?? null;
147
+ }
148
+
149
+ /** Whether any orchestration extension has registered roles. */
150
+ export function hasRoleProvider(): boolean {
151
+ return _provider !== null;
152
+ }
153
+
154
+ /**
155
+ * Build the system-prompt block describing available roles. Returns '' when no
156
+ * roles are registered, so non-orchestration users pay nothing in tokens.
157
+ */
158
+ export function buildRolesPrompt(): string {
159
+ const roles = listRoleSpecs();
160
+ if (roles.length === 0) return '';
161
+
162
+ const agents = roles.filter((r) => r.kind === 'agent');
163
+ const categories = roles.filter((r) => r.kind === 'category');
164
+
165
+ const lines: string[] = [
166
+ 'You can delegate work to specialist sub-agents via the `delegate` tool.',
167
+ 'Each role runs with its own model, tools, and system prompt — pick by role, not by model name.',
168
+ '',
169
+ ];
170
+
171
+ if (agents.length > 0) {
172
+ lines.push('Read-only agents (`delegate(task, agent="…")`):');
173
+ for (const r of agents) lines.push(`- ${r.name}: ${r.description}`);
174
+ lines.push('');
175
+ }
176
+
177
+ if (categories.length > 0) {
178
+ lines.push('Implementation lanes (`delegate(task, category="…")`):');
179
+ for (const r of categories) lines.push(`- ${r.name}: ${r.description}`);
180
+ lines.push('');
181
+ }
182
+
183
+ lines.push(
184
+ 'Use `delegate_parallel([...])` to run several delegates at once when the sub-tasks are independent.',
185
+ );
186
+
187
+ return lines.join('\n');
188
+ }
@@ -0,0 +1,207 @@
1
+ import {test, expect} from 'bun:test';
2
+ import {
3
+ runAgent,
4
+ type ConversationMessage,
5
+ type AgentRunEvent,
6
+ type RunAgentOptions,
7
+ } from './run.js';
8
+
9
+ type FakeEvent =
10
+ | {type: 'text'; content: string}
11
+ | {type: 'tool_use'; toolCall: {id: string; name: string; arguments: string}}
12
+ | {
13
+ type: 'done';
14
+ usage?: {
15
+ promptTokens: number;
16
+ completionTokens: number;
17
+ totalTokens: number;
18
+ cachedTokens?: number;
19
+ };
20
+ }
21
+ | {type: 'error'; content: string};
22
+
23
+ /** A provider stub that replays one scripted response per round. */
24
+ function makeProvider(responses: FakeEvent[][]) {
25
+ return {
26
+ async *stream(): AsyncGenerator<FakeEvent> {
27
+ const chunks = responses.shift() ?? [];
28
+ for (const chunk of chunks) yield chunk;
29
+ },
30
+ };
31
+ }
32
+
33
+ async function collect(gen: AsyncGenerator<AgentRunEvent>): Promise<AgentRunEvent[]> {
34
+ const out: AgentRunEvent[] = [];
35
+ for await (const ev of gen) out.push(ev);
36
+ return out;
37
+ }
38
+
39
+ function opts(
40
+ overrides: {messages: ConversationMessage[]; provider: unknown} & Record<string, unknown>,
41
+ ): RunAgentOptions {
42
+ return {
43
+ tools: [],
44
+ model: 'test-model',
45
+ systemPrompt: 'You are helpful.',
46
+ providerConfig: {model: 'test-model', apiKey: 'k', baseUrl: 'https://example.test'},
47
+ executeTool: async () => ({content: 'ok'}),
48
+ ...overrides,
49
+ } as unknown as RunAgentOptions;
50
+ }
51
+
52
+ test('runAgent: yields text and records the assistant message', async () => {
53
+ const messages: ConversationMessage[] = [{role: 'user', content: 'Hi'}];
54
+ const provider = makeProvider([
55
+ [
56
+ {type: 'text', content: 'Hello'},
57
+ {type: 'done', usage: {promptTokens: 10, completionTokens: 2, totalTokens: 12}},
58
+ ],
59
+ ]);
60
+
61
+ const events = await collect(runAgent(opts({messages, provider})));
62
+
63
+ expect(events.some((e) => e.type === 'text-delta')).toBe(true);
64
+ const done = events.find((e) => e.type === 'done');
65
+ expect(done && done.type === 'done' ? done.usage.inputTokens : -1).toBe(10);
66
+ expect(messages[messages.length - 1]).toEqual({role: 'assistant', content: 'Hello'});
67
+ });
68
+
69
+ test('runAgent: executes tool calls and feeds results back to the model', async () => {
70
+ const messages: ConversationMessage[] = [{role: 'user', content: 'Read a.ts'}];
71
+ const provider = makeProvider([
72
+ [
73
+ {type: 'tool_use', toolCall: {id: 'c1', name: 'read_file', arguments: '{"path":"a.ts"}'}},
74
+ {type: 'done'},
75
+ ],
76
+ [
77
+ {type: 'text', content: 'Got it.'},
78
+ {type: 'done', usage: {promptTokens: 20, completionTokens: 5, totalTokens: 25}},
79
+ ],
80
+ ]);
81
+
82
+ const events = await collect(
83
+ runAgent(
84
+ opts({
85
+ messages,
86
+ provider,
87
+ executeTool: async (name: string, args: string, id: string) => {
88
+ expect(name).toBe('read_file');
89
+ expect(args).toBe('{"path":"a.ts"}');
90
+ expect(id).toBe('c1');
91
+ return {content: 'line 1: hi'};
92
+ },
93
+ }),
94
+ ),
95
+ );
96
+
97
+ expect(events.some((e) => e.type === 'tool-start')).toBe(true);
98
+ expect(events.some((e) => e.type === 'tool-end')).toBe(true);
99
+ expect(
100
+ messages.some((m) => m.role === 'tool' && (m as {tool_call_id: string}).tool_call_id === 'c1'),
101
+ ).toBe(true);
102
+ expect(messages[messages.length - 1]).toEqual({role: 'assistant', content: 'Got it.'});
103
+ });
104
+
105
+ test('runAgent: enforces maxRounds', async () => {
106
+ const messages: ConversationMessage[] = [{role: 'user', content: 'loop'}];
107
+ const provider = makeProvider([
108
+ [
109
+ {type: 'tool_use', toolCall: {id: 'c1', name: 'bash', arguments: '{"command":"a"}'}},
110
+ {type: 'done'},
111
+ ],
112
+ [
113
+ {type: 'tool_use', toolCall: {id: 'c2', name: 'bash', arguments: '{"command":"b"}'}},
114
+ {type: 'done'},
115
+ ],
116
+ ]);
117
+
118
+ const events = await collect(runAgent(opts({messages, provider, maxRounds: 1})));
119
+
120
+ const notices = events.filter((e): e is {type: 'notice'; text: string} => e.type === 'notice');
121
+ expect(notices.some((n) => n.text.includes('Max tool rounds'))).toBe(true);
122
+ });
123
+
124
+ test('runAgent: stops early when an identical tool call repeats', async () => {
125
+ const messages: ConversationMessage[] = [{role: 'user', content: 'spin'}];
126
+ // Same name + identical arguments every round — mirrors a stuck model.
127
+ const same = {
128
+ type: 'tool_use' as const,
129
+ toolCall: {id: 'c', name: 'bash', arguments: '{"command":"x"}'},
130
+ };
131
+ const provider = makeProvider([
132
+ [same, {type: 'done'}],
133
+ [same, {type: 'done'}],
134
+ [same, {type: 'done'}],
135
+ [same, {type: 'done'}],
136
+ [same, {type: 'done'}],
137
+ [same, {type: 'done'}],
138
+ [same, {type: 'done'}],
139
+ ]);
140
+
141
+ const events = await collect(runAgent(opts({messages, provider, maxRounds: 50})));
142
+
143
+ const notices = events.filter((e): e is {type: 'notice'; text: string} => e.type === 'notice');
144
+ expect(notices.some((n) => n.text.includes('loop detected'))).toBe(true);
145
+ expect(notices.some((n) => n.text.includes('Max tool rounds'))).toBe(false);
146
+ });
147
+
148
+ test('runAgent: a pre-aborted signal ends the turn immediately', async () => {
149
+ const messages: ConversationMessage[] = [{role: 'user', content: 'Hi'}];
150
+ const provider = makeProvider([]);
151
+ const controller = new AbortController();
152
+ controller.abort();
153
+
154
+ const events = await collect(runAgent(opts({messages, provider, signal: controller.signal})));
155
+ const types = events.map((e) => e.type);
156
+
157
+ expect(types).toContain('aborted');
158
+ expect(types).not.toContain('done');
159
+ });
160
+
161
+ test('runAgent: the round cap degrades into a tools-disabled summary', async () => {
162
+ const messages: ConversationMessage[] = [{role: 'user', content: 'Do a long task'}];
163
+ const toolCountsPerCall: number[] = [];
164
+
165
+ // Round 1 asks for a tool; the wrap-up call must be made with tools withheld.
166
+ const provider = {
167
+ async *stream(o: {tools?: unknown[]}): AsyncGenerator<FakeEvent> {
168
+ toolCountsPerCall.push(Array.isArray(o.tools) ? o.tools.length : -1);
169
+ if (toolCountsPerCall.length === 1) {
170
+ yield {
171
+ type: 'tool_use',
172
+ toolCall: {id: 'c1', name: 'read_file', arguments: '{"path":"a.ts"}'},
173
+ };
174
+ yield {type: 'done'};
175
+ } else {
176
+ yield {type: 'text', content: 'Summary: reached the step cap, nothing else done.'};
177
+ yield {type: 'done'};
178
+ }
179
+ },
180
+ };
181
+
182
+ const events = await collect(
183
+ runAgent(
184
+ opts({
185
+ messages,
186
+ provider,
187
+ maxRounds: 1,
188
+ tools: [
189
+ {type: 'function', function: {name: 'read_file', description: 'read', parameters: {}}},
190
+ ],
191
+ }),
192
+ ),
193
+ );
194
+
195
+ const types = events.map((e) => e.type);
196
+ expect(types).toContain('done');
197
+ expect(types).toContain('notice');
198
+
199
+ // Two model calls: the capped round (1 tool) then the wrap-up (0 tools).
200
+ expect(toolCountsPerCall.length).toBe(2);
201
+ expect(toolCountsPerCall[0]).toBe(1);
202
+ expect(toolCountsPerCall[1]).toBe(0);
203
+
204
+ // The forced summary is streamed and persisted so the user always sees it.
205
+ expect(events.some((e) => e.type === 'text-delta' && e.content.includes('Summary'))).toBe(true);
206
+ expect(messages[messages.length - 1]?.content).toContain('Summary');
207
+ });