@pal-code/core 0.0.10 → 0.0.12
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 +1 -1
- package/src/agent/fallback.ts +13 -2
- package/src/agent/file-roles.ts +183 -0
- package/src/agent/frontmatter.ts +105 -0
- package/src/agent/roles.ts +41 -5
- package/src/agent/run.ts +118 -4
- package/src/agent/skills.ts +177 -0
- package/src/agent/subagent-status.ts +78 -0
- package/src/config.ts +47 -2
- package/src/diagnostics-checks.ts +201 -0
- package/src/diagnostics.ts +173 -0
- package/src/extensions.ts +17 -1
- package/src/index.ts +21 -0
- package/src/lifecycle.ts +109 -0
- package/src/provider/openrouter.ts +40 -9
- package/src/provider/registry.ts +16 -1
- package/src/registry.ts +5 -4
- package/src/tools/definitions.ts +16 -2
- package/src/tools/executor.ts +229 -13
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-diagnostics after edits (roadmap #1, Phase 1): biome + incremental tsc.
|
|
3
|
+
*
|
|
4
|
+
* Contract: `noteEditedFile()` is fire-and-forget — it schedules a debounced
|
|
5
|
+
* check run and returns immediately, so the edit tool handler never waits on
|
|
6
|
+
* checks. `takeDiagnosticsLine()` hands back exactly one line for the next
|
|
7
|
+
* model round, bounded by the total budget; infrastructure failures (missing
|
|
8
|
+
* tools, crash, timeout) resolve to `null` and are silently skipped.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {loadAgentConfig, resolveProjectRoot} from './config.js';
|
|
12
|
+
import type {DiagnosticsMode} from './config.js';
|
|
13
|
+
import {log} from './logger.js';
|
|
14
|
+
import {runChecks} from './diagnostics-checks.js';
|
|
15
|
+
|
|
16
|
+
export type {DiagnosticsMode} from './config.js';
|
|
17
|
+
|
|
18
|
+
export interface DiagnosticError {
|
|
19
|
+
path: string;
|
|
20
|
+
line: number;
|
|
21
|
+
message: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type DiagnosticsChecker = (
|
|
25
|
+
files: readonly string[],
|
|
26
|
+
ctx: {cwd: string; budgetMs: number},
|
|
27
|
+
) => Promise<DiagnosticError[] | null>;
|
|
28
|
+
|
|
29
|
+
const DEFAULT_TIMING = {debounceMs: 200, budgetMs: 2000};
|
|
30
|
+
const MAX_SHOWN_ERRORS = 3;
|
|
31
|
+
const MAX_LINE_CHARS = 240;
|
|
32
|
+
|
|
33
|
+
interface DiagnosticsCycle {
|
|
34
|
+
files: Set<string>;
|
|
35
|
+
deadline: number;
|
|
36
|
+
started: boolean;
|
|
37
|
+
startTimer: ReturnType<typeof setTimeout> | null;
|
|
38
|
+
capTimer: ReturnType<typeof setTimeout> | null;
|
|
39
|
+
result: Promise<string | null>;
|
|
40
|
+
settle: (line: string | null) => void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let cycle: DiagnosticsCycle | null = null;
|
|
44
|
+
let checkerOverride: DiagnosticsChecker | null = null;
|
|
45
|
+
let modeOverride: DiagnosticsMode | null = null;
|
|
46
|
+
let timing = {...DEFAULT_TIMING};
|
|
47
|
+
|
|
48
|
+
export function getDiagnosticsMode(): DiagnosticsMode {
|
|
49
|
+
return modeOverride ?? loadAgentConfig().diagnostics;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `[]` (clean) → the success line; errors → one `✗ path:line - …` line. */
|
|
53
|
+
export function formatDiagnosticsLine(errors: readonly DiagnosticError[]): string {
|
|
54
|
+
if (errors.length === 0) return '✓ edit ok';
|
|
55
|
+
const head = errors[0];
|
|
56
|
+
const shown = errors
|
|
57
|
+
.slice(0, MAX_SHOWN_ERRORS)
|
|
58
|
+
.map((e) => e.message.replace(/\s+/g, ' ').trim())
|
|
59
|
+
.join('; ');
|
|
60
|
+
const line = `✗ ${head.path}:${head.line} - ${shown}`;
|
|
61
|
+
return line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS - 3)}...` : line;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Record a successful edit/write. Schedules a coalesced check run and returns
|
|
66
|
+
* immediately — never blocks the tool handler, never throws into it.
|
|
67
|
+
*/
|
|
68
|
+
export function noteEditedFile(path: string): void {
|
|
69
|
+
if (getDiagnosticsMode() === 'off') return;
|
|
70
|
+
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
const active = cycle;
|
|
73
|
+
let target: DiagnosticsCycle;
|
|
74
|
+
if (active !== null && !active.started && now < active.deadline) {
|
|
75
|
+
target = active;
|
|
76
|
+
if (target.startTimer !== null) {
|
|
77
|
+
clearTimeout(target.startTimer);
|
|
78
|
+
target.startTimer = null;
|
|
79
|
+
}
|
|
80
|
+
} else {
|
|
81
|
+
target = createCycle(now, active?.files);
|
|
82
|
+
if (active !== null) finish(active, null);
|
|
83
|
+
cycle = target;
|
|
84
|
+
}
|
|
85
|
+
target.files.add(path);
|
|
86
|
+
scheduleStart(target, now);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* One line for the next model round (`✓ edit ok` / `✗ …`), or `null` when
|
|
91
|
+
* there is nothing to report (no edits, checks skipped, or budget exceeded).
|
|
92
|
+
* Resolves no later than the cycle's deadline.
|
|
93
|
+
*/
|
|
94
|
+
export async function takeDiagnosticsLine(): Promise<string | null> {
|
|
95
|
+
const c = cycle;
|
|
96
|
+
if (c === null) return null;
|
|
97
|
+
const line = await c.result;
|
|
98
|
+
if (cycle === c) cycle = null;
|
|
99
|
+
return line;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function createCycle(now: number, seedFiles?: ReadonlySet<string>): DiagnosticsCycle {
|
|
103
|
+
const gate = Promise.withResolvers<string | null>();
|
|
104
|
+
const c: DiagnosticsCycle = {
|
|
105
|
+
files: new Set(seedFiles),
|
|
106
|
+
deadline: now + timing.budgetMs,
|
|
107
|
+
started: false,
|
|
108
|
+
startTimer: null,
|
|
109
|
+
capTimer: null,
|
|
110
|
+
result: gate.promise,
|
|
111
|
+
settle: gate.resolve,
|
|
112
|
+
};
|
|
113
|
+
c.capTimer = setTimeout(() => finish(c, null), timing.budgetMs);
|
|
114
|
+
return c;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function scheduleStart(c: DiagnosticsCycle, now: number): void {
|
|
118
|
+
const delay = Math.min(timing.debounceMs, Math.max(0, c.deadline - now));
|
|
119
|
+
c.startTimer = setTimeout(() => {
|
|
120
|
+
c.startTimer = null;
|
|
121
|
+
startChecks(c);
|
|
122
|
+
}, delay);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function finish(c: DiagnosticsCycle, line: string | null): void {
|
|
126
|
+
if (c.startTimer !== null) {
|
|
127
|
+
clearTimeout(c.startTimer);
|
|
128
|
+
c.startTimer = null;
|
|
129
|
+
}
|
|
130
|
+
if (c.capTimer !== null) {
|
|
131
|
+
clearTimeout(c.capTimer);
|
|
132
|
+
c.capTimer = null;
|
|
133
|
+
}
|
|
134
|
+
c.settle(line);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function startChecks(c: DiagnosticsCycle): void {
|
|
138
|
+
c.started = true;
|
|
139
|
+
const budgetMs = Math.max(1, c.deadline - Date.now());
|
|
140
|
+
const files = [...c.files];
|
|
141
|
+
const check = checkerOverride ?? runChecks;
|
|
142
|
+
void Promise.resolve()
|
|
143
|
+
.then(() => check(files, {cwd: resolveProjectRoot() ?? process.cwd(), budgetMs}))
|
|
144
|
+
.then(
|
|
145
|
+
(errors) => finish(c, errors === null ? null : formatDiagnosticsLine(errors)),
|
|
146
|
+
(err: unknown) => {
|
|
147
|
+
log('diagnostics-error', {message: err instanceof Error ? err.message : String(err)});
|
|
148
|
+
finish(c, null);
|
|
149
|
+
},
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function setDiagnosticsCheckerForTest(next: DiagnosticsChecker | null): void {
|
|
154
|
+
checkerOverride = next;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function setDiagnosticsModeForTest(next: DiagnosticsMode | null): void {
|
|
158
|
+
modeOverride = next;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function setDiagnosticsTimingForTest(
|
|
162
|
+
next: {debounceMs: number; budgetMs: number} | null,
|
|
163
|
+
): void {
|
|
164
|
+
timing = next === null ? {...DEFAULT_TIMING} : {...next};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function clearDiagnosticsForTest(): void {
|
|
168
|
+
if (cycle !== null) finish(cycle, null);
|
|
169
|
+
cycle = null;
|
|
170
|
+
checkerOverride = null;
|
|
171
|
+
modeOverride = null;
|
|
172
|
+
timing = {...DEFAULT_TIMING};
|
|
173
|
+
}
|
package/src/extensions.ts
CHANGED
|
@@ -35,6 +35,7 @@ import {homedir} from 'node:os';
|
|
|
35
35
|
import {isAbsolute, join, relative} from 'node:path';
|
|
36
36
|
import type {ToolDef} from './tools/definitions.js';
|
|
37
37
|
import type {ToolConfig} from './config.js';
|
|
38
|
+
import type {LifecycleHandlers} from './lifecycle.js';
|
|
38
39
|
import {clearRoleProvider} from './agent/roles.js';
|
|
39
40
|
|
|
40
41
|
/** Tool handler function signature. */
|
|
@@ -54,11 +55,20 @@ export interface ToolExtension {
|
|
|
54
55
|
* `@pal-code/agents` registers the role provider used by core's `delegate`.
|
|
55
56
|
*/
|
|
56
57
|
setup?: () => void | Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Optional lifecycle handlers, called by the agent loop and tool executor
|
|
60
|
+
* at the points the roadmap's Hooks section specifies (turn boundaries,
|
|
61
|
+
* tool dispatch, failures). Collected during `loadExtensions()` — same
|
|
62
|
+
* pattern as tools/handlers.
|
|
63
|
+
*/
|
|
64
|
+
lifecycle?: LifecycleHandlers;
|
|
57
65
|
}
|
|
58
66
|
|
|
59
67
|
export interface LoadedExtensions {
|
|
60
68
|
tools: ToolDef[];
|
|
61
69
|
handlers: Record<string, ToolHandler>;
|
|
70
|
+
/** Lifecycle handler sets, one entry per extension that declared them. */
|
|
71
|
+
lifecycle: LifecycleHandlers[];
|
|
62
72
|
/** Package names that loaded successfully, in input order. */
|
|
63
73
|
loaded: string[];
|
|
64
74
|
/** Package names that failed, with the reason. */
|
|
@@ -188,6 +198,7 @@ export async function loadExtensions(
|
|
|
188
198
|
const roots = options.roots ?? defaultExtensionRoots();
|
|
189
199
|
const allTools: ToolDef[] = [];
|
|
190
200
|
const allHandlers: Record<string, ToolHandler> = {};
|
|
201
|
+
const allLifecycle: LifecycleHandlers[] = [];
|
|
191
202
|
const loaded: string[] = [];
|
|
192
203
|
const failed: Array<{pkg: string; reason: string}> = [];
|
|
193
204
|
|
|
@@ -208,6 +219,11 @@ export async function loadExtensions(
|
|
|
208
219
|
|
|
209
220
|
allTools.push(...ext.tools);
|
|
210
221
|
Object.assign(allHandlers, ext.handlers);
|
|
222
|
+
// Kept per-extension (not merged key-wise like handlers) so one
|
|
223
|
+
// extension's onToolCall cannot clobber another's at load time.
|
|
224
|
+
if (ext.lifecycle && typeof ext.lifecycle === 'object') {
|
|
225
|
+
allLifecycle.push(ext.lifecycle);
|
|
226
|
+
}
|
|
211
227
|
loaded.push(pkg);
|
|
212
228
|
|
|
213
229
|
// Extension-granted capabilities (non-tool) — e.g. the role provider.
|
|
@@ -230,5 +246,5 @@ export async function loadExtensions(
|
|
|
230
246
|
}
|
|
231
247
|
}
|
|
232
248
|
|
|
233
|
-
return {tools: allTools, handlers: allHandlers, loaded, failed};
|
|
249
|
+
return {tools: allTools, handlers: allHandlers, lifecycle: allLifecycle, loaded, failed};
|
|
234
250
|
}
|
package/src/index.ts
CHANGED
|
@@ -55,6 +55,13 @@ export type {
|
|
|
55
55
|
} from './agent/run.js';
|
|
56
56
|
export {onAgentEvent, emitAgentEvent} from './agent/events.js';
|
|
57
57
|
export type {AgentEvent as AgentLifecycleEvent} from './agent/events.js';
|
|
58
|
+
export {
|
|
59
|
+
subagentSpawned,
|
|
60
|
+
subagentSettled,
|
|
61
|
+
getSubagentStatus,
|
|
62
|
+
onSubagentStatusChange,
|
|
63
|
+
} from './agent/subagent-status.js';
|
|
64
|
+
export type {SubagentStatus} from './agent/subagent-status.js';
|
|
58
65
|
export {
|
|
59
66
|
setTodos,
|
|
60
67
|
getTodos,
|
|
@@ -80,6 +87,9 @@ export {
|
|
|
80
87
|
buildRolesPrompt,
|
|
81
88
|
} from './agent/roles.js';
|
|
82
89
|
export type {RoleSpec, RoleKind, RoleProvider, PrimarySpec} from './agent/roles.js';
|
|
90
|
+
export {buildSkillsPrompt, clearSkillsCache, listSkills} from './agent/skills.js';
|
|
91
|
+
export type {Skill} from './agent/skills.js';
|
|
92
|
+
export {clearFileRolesCache} from './agent/file-roles.js';
|
|
83
93
|
|
|
84
94
|
// Config
|
|
85
95
|
export {loadAgentConfig, isPathIgnored, clearConfigCache, resolveProjectRoot} from './config.js';
|
|
@@ -120,6 +130,17 @@ export type {
|
|
|
120
130
|
LoadExtensionsOptions,
|
|
121
131
|
} from './extensions.js';
|
|
122
132
|
|
|
133
|
+
// Extension lifecycle hooks
|
|
134
|
+
export {emitLifecycleEvent, registerExtensionLifecycle} from './lifecycle.js';
|
|
135
|
+
export type {
|
|
136
|
+
TurnContext,
|
|
137
|
+
ToolCallEvent,
|
|
138
|
+
ErrorEvent,
|
|
139
|
+
LifecycleEventMap,
|
|
140
|
+
LifecycleEventName,
|
|
141
|
+
LifecycleHandlers,
|
|
142
|
+
} from './lifecycle.js';
|
|
143
|
+
|
|
123
144
|
// Repo Map
|
|
124
145
|
export {buildRepoMap} from './repo-map.js';
|
|
125
146
|
|
package/src/lifecycle.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extension lifecycle hooks — roadmap #6, `## 🪝 Extension Lifecycle Hooks`.
|
|
3
|
+
*
|
|
4
|
+
* Lets an extension observe agent activity through the optional `lifecycle`
|
|
5
|
+
* field on `ToolExtension`: turn boundaries, tool dispatch, and failures.
|
|
6
|
+
* `loadExtensions()` collects the handlers (same pattern as tools/handlers);
|
|
7
|
+
* whoever loads them calls {@link registerExtensionLifecycle}, and the agent
|
|
8
|
+
* loop / tool executor call {@link emitLifecycleEvent} at the points the
|
|
9
|
+
* roadmap's Implementation subsection enumerates — before/after the loop,
|
|
10
|
+
* inside `executeTool`.
|
|
11
|
+
*
|
|
12
|
+
* The store lives in the shared {@link registry} global slot for the same
|
|
13
|
+
* reason extension tools do: an extension installed under `~/.pal/extensions`
|
|
14
|
+
* resolves its own copy of core, so a module-local store would swallow the
|
|
15
|
+
* registration and the CLI's copy would never fire it.
|
|
16
|
+
*
|
|
17
|
+
* A handler that throws or rejects is caught and logged — never propagated.
|
|
18
|
+
* Hooks run alongside the agent loop, so a broken extension must not fail the
|
|
19
|
+
* tool call or the turn (same isolation policy as `setup()`).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import {log} from './logger.js';
|
|
23
|
+
import {registry} from './registry.js';
|
|
24
|
+
|
|
25
|
+
/** Context handed to turn-boundary hooks. */
|
|
26
|
+
export interface TurnContext {
|
|
27
|
+
/** Unique id for this turn (one `runAgent` invocation). */
|
|
28
|
+
readonly turnId: string;
|
|
29
|
+
/** Active primary agent name; `''` when the turn has no primary (e.g. a delegate child). */
|
|
30
|
+
readonly primary: string;
|
|
31
|
+
/** Messages in the conversation so far. */
|
|
32
|
+
readonly messageCount: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** One completed tool dispatch. */
|
|
36
|
+
export interface ToolCallEvent {
|
|
37
|
+
readonly tool: string;
|
|
38
|
+
readonly args: Record<string, unknown>;
|
|
39
|
+
readonly durationMs: number;
|
|
40
|
+
readonly success: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A failure observed while dispatching a tool call. */
|
|
44
|
+
export interface ErrorEvent {
|
|
45
|
+
readonly error: Error;
|
|
46
|
+
/** What was happening when it failed, e.g. `tool:read_file`. */
|
|
47
|
+
readonly context: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Payload carried by each lifecycle event, keyed by event name. */
|
|
51
|
+
export interface LifecycleEventMap {
|
|
52
|
+
onTurnStart: TurnContext;
|
|
53
|
+
onTurnEnd: TurnContext;
|
|
54
|
+
onToolCall: ToolCallEvent;
|
|
55
|
+
onError: ErrorEvent;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The lifecycle event names an extension can observe. */
|
|
59
|
+
export type LifecycleEventName = keyof LifecycleEventMap;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The handlers an extension declares under `ToolExtension.lifecycle`.
|
|
63
|
+
*
|
|
64
|
+
* Derived from {@link LifecycleEventMap} so registration and emission are
|
|
65
|
+
* checked against one source; the shape is the roadmap's inline interface.
|
|
66
|
+
*/
|
|
67
|
+
export type LifecycleHandlers = {
|
|
68
|
+
readonly [K in LifecycleEventName]?: (ev: LifecycleEventMap[K]) => void | Promise<void>;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Replace the registered lifecycle hooks. Called when extensions load and on
|
|
73
|
+
* `/reload` — replace rather than merge so a removed extension's hooks neither
|
|
74
|
+
* linger nor duplicate (same semantics as `registerExtensionTools`).
|
|
75
|
+
*/
|
|
76
|
+
export function registerExtensionLifecycle(hooks: readonly LifecycleHandlers[]): void {
|
|
77
|
+
registry.lifecycleHooks = [...hooks];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Notify every registered lifecycle hook for `event`, in registration order.
|
|
82
|
+
*
|
|
83
|
+
* Handlers are awaited sequentially so async hooks complete deterministically
|
|
84
|
+
* before the turn moves on. A hook that throws or rejects is caught and logged
|
|
85
|
+
* (`PAL_DEBUG=1`); the remaining hooks still run. Never throws — a broken
|
|
86
|
+
* extension cannot fail the tool call or the turn. Returns immediately when
|
|
87
|
+
* nothing is registered for `event`, so turns without lifecycle extensions pay
|
|
88
|
+
* only one empty-array check.
|
|
89
|
+
*/
|
|
90
|
+
export async function emitLifecycleEvent<K extends LifecycleEventName>(
|
|
91
|
+
event: K,
|
|
92
|
+
payload: LifecycleEventMap[K],
|
|
93
|
+
): Promise<void> {
|
|
94
|
+
const hooks = registry.lifecycleHooks;
|
|
95
|
+
if (hooks.length === 0) return;
|
|
96
|
+
|
|
97
|
+
for (const set of hooks) {
|
|
98
|
+
const handler = set[event];
|
|
99
|
+
if (handler === undefined) continue;
|
|
100
|
+
try {
|
|
101
|
+
await handler(payload);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
// Isolation, not silence: narrow and record. Console output would smear
|
|
104
|
+
// the TUI frame mid-turn — the same reason setup() failures avoid it.
|
|
105
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
106
|
+
log('lifecycle-hook-error', {event, message});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -7,16 +7,40 @@ import type {Provider, ProviderConfig, ProviderModel, StreamEvent, Usage} from '
|
|
|
7
7
|
import {randomBytes} from 'crypto';
|
|
8
8
|
import {log} from '../logger.js';
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
11
|
+
|
|
12
|
+
/** `len` base62 chars from crypto random bytes.
|
|
13
|
+
* 248 = 62 × 4, so every accepted byte maps uniformly onto the alphabet —
|
|
14
|
+
* bytes ≥ 248 are rejected rather than taken modulo, keeping the distribution
|
|
15
|
+
* exactly uniform. */
|
|
16
|
+
function randomBase62(len: number): string {
|
|
17
|
+
let out = '';
|
|
18
|
+
while (out.length < len) {
|
|
19
|
+
for (const b of randomBytes(len - out.length)) {
|
|
20
|
+
if (b < 248) out += BASE62[b % 62];
|
|
21
|
+
if (out.length === len) break;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Expand header-value tokens.
|
|
28
|
+
* `__sesid__` → `ses_` + 12 lowercase hex + 14 base62
|
|
11
29
|
* `__random:32__` → 32-char random hex
|
|
12
30
|
* `__random:ses_:32__` → `ses_` + 32-char random hex
|
|
31
|
+
* Anything else is returned unchanged.
|
|
13
32
|
*/
|
|
14
|
-
function expandRandomValue(val: string): string {
|
|
33
|
+
export function expandRandomValue(val: string): string {
|
|
34
|
+
if (val === '__sesid__') {
|
|
35
|
+
return `ses_${randomBytes(6).toString('hex')}${randomBase62(14)}`;
|
|
36
|
+
}
|
|
15
37
|
const m = val.match(/^__random(?::([^:]+))?:(\d+)__$/);
|
|
16
38
|
if (!m) return val;
|
|
17
39
|
const prefix = m[1] ?? '';
|
|
18
40
|
const len = Number(m[2]);
|
|
19
|
-
const hex = randomBytes(Math.ceil(len / 2))
|
|
41
|
+
const hex = randomBytes(Math.ceil(len / 2))
|
|
42
|
+
.toString('hex')
|
|
43
|
+
.slice(0, len);
|
|
20
44
|
return prefix + hex;
|
|
21
45
|
}
|
|
22
46
|
|
|
@@ -211,7 +235,10 @@ class OpenRouterProvider implements Provider {
|
|
|
211
235
|
if (data === '[DONE]') continue;
|
|
212
236
|
|
|
213
237
|
try {
|
|
214
|
-
|
|
238
|
+
// Providers/gateways occasionally emit raw NUL bytes, which make
|
|
239
|
+
// JSON.parse throw — the catch below would then drop the whole chunk,
|
|
240
|
+
// losing tool-call argument fragments. Strip them before parsing.
|
|
241
|
+
const parsed = JSON.parse(data.replaceAll('\u0000', ''));
|
|
215
242
|
const choice = parsed.choices?.[0];
|
|
216
243
|
|
|
217
244
|
// Extract usage from chunk (Gemini puts it in the last chunk)
|
|
@@ -230,9 +257,10 @@ class OpenRouterProvider implements Provider {
|
|
|
230
257
|
|
|
231
258
|
const delta = choice.delta;
|
|
232
259
|
|
|
233
|
-
// Text content
|
|
260
|
+
// Text content — strip escaped NULs that survive JSON.parse
|
|
261
|
+
// (stray null bytes corrupt rendered text and commands downstream).
|
|
234
262
|
if (delta?.content) {
|
|
235
|
-
yield {type: 'text', content: delta.content};
|
|
263
|
+
yield {type: 'text', content: delta.content.replaceAll('\u0000', '')};
|
|
236
264
|
}
|
|
237
265
|
|
|
238
266
|
// Tool calls — accumulate arguments across chunks.
|
|
@@ -263,9 +291,12 @@ class OpenRouterProvider implements Provider {
|
|
|
263
291
|
toolCallAccumulators.set(idxKey, existing);
|
|
264
292
|
}
|
|
265
293
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
if (tc.
|
|
294
|
+
// Strip NULs at the read point: escaped null bytes survive
|
|
295
|
+
// JSON.parse and would otherwise corrupt ids/names/arguments.
|
|
296
|
+
if (tc.id) existing.id = tc.id.replaceAll('\u0000', '');
|
|
297
|
+
if (tc.function?.name) existing.name = tc.function.name.replaceAll('\u0000', '');
|
|
298
|
+
if (tc.function?.arguments)
|
|
299
|
+
existing.arguments += tc.function.arguments.replaceAll('\u0000', '');
|
|
269
300
|
// Capture Gemini's extra_content (contains thought_signature)
|
|
270
301
|
if (tc.extra_content && !existing.extra_content) {
|
|
271
302
|
existing.extra_content = tc.extra_content;
|
package/src/provider/registry.ts
CHANGED
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
* Custom providers can be added via `~/.pal/providers.json` — an array of
|
|
13
13
|
* ProviderDef objects. Use the `headers` field to inject custom HTTP headers
|
|
14
14
|
* (e.g. User-Agent overrides). Header values containing `__random:N__` are
|
|
15
|
-
* expanded to N-character random hex strings at
|
|
15
|
+
* expanded to N-character random hex strings at request time; `__sesid__`
|
|
16
|
+
* expands to a fresh session-shaped id (`ses_` + 12 hex + 14 base62).
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
19
|
export interface ProviderDef {
|
|
@@ -38,6 +39,12 @@ export interface ProviderDef {
|
|
|
38
39
|
freeModelPattern?: string;
|
|
39
40
|
/** Custom HTTP headers sent with every request (e.g. User-Agent overrides). */
|
|
40
41
|
headers?: Record<string, string>;
|
|
42
|
+
/**
|
|
43
|
+
* Text appended after the model's own system instructions when this provider
|
|
44
|
+
* serves the turn — carried in `messages[0].content`. Absent → the system
|
|
45
|
+
* prompt is untouched.
|
|
46
|
+
*/
|
|
47
|
+
systemPromptAppend?: string;
|
|
41
48
|
/** Short hint shown in the provider picker UI. */
|
|
42
49
|
hint?: string;
|
|
43
50
|
/** Provider id alias (e.g. "opencode" → resolves to this provider's id). */
|
|
@@ -220,3 +227,11 @@ export function providerForModel(
|
|
|
220
227
|
const fallback = configured ?? getProvider('gemini')!;
|
|
221
228
|
return {provider: fallback, model: modelSpec};
|
|
222
229
|
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Append a provider's `systemPromptAppend` block to a system prompt.
|
|
233
|
+
* No field → the prompt comes back byte-for-byte unchanged.
|
|
234
|
+
*/
|
|
235
|
+
export function withSystemPromptAppend(base: string, def: {systemPromptAppend?: string}): string {
|
|
236
|
+
return def.systemPromptAppend ? `${base}\n\n${def.systemPromptAppend}` : base;
|
|
237
|
+
}
|
package/src/registry.ts
CHANGED
|
@@ -31,13 +31,11 @@
|
|
|
31
31
|
|
|
32
32
|
import type {ToolConfig} from './config.js';
|
|
33
33
|
import type {RoleProvider} from './agent/roles.js';
|
|
34
|
+
import type {LifecycleHandlers} from './lifecycle.js';
|
|
34
35
|
import type {ToolDef} from './tools/definitions.js';
|
|
35
36
|
|
|
36
37
|
/** A tool handler: `(args, config) => Promise<string>`. */
|
|
37
|
-
export type ToolHandlerFn = (
|
|
38
|
-
args: Record<string, unknown>,
|
|
39
|
-
config: ToolConfig,
|
|
40
|
-
) => Promise<string>;
|
|
38
|
+
export type ToolHandlerFn = (args: Record<string, unknown>, config: ToolConfig) => Promise<string>;
|
|
41
39
|
|
|
42
40
|
export interface CoreRegistry {
|
|
43
41
|
/** Orchestration role provider, registered by `@pal-code/agents`. */
|
|
@@ -46,6 +44,8 @@ export interface CoreRegistry {
|
|
|
46
44
|
extensionTools: ToolDef[];
|
|
47
45
|
/** Handlers for {@link extensionTools}, keyed by tool name. */
|
|
48
46
|
extensionHandlers: Record<string, ToolHandlerFn>;
|
|
47
|
+
/** Lifecycle hooks declared by loaded extensions (roadmap #6). */
|
|
48
|
+
lifecycleHooks: LifecycleHandlers[];
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
const KEY = '__pal_core_registry__';
|
|
@@ -60,4 +60,5 @@ export const registry: CoreRegistry = (store[KEY] ??= {
|
|
|
60
60
|
roleProvider: null,
|
|
61
61
|
extensionTools: [],
|
|
62
62
|
extensionHandlers: {},
|
|
63
|
+
lifecycleHooks: [],
|
|
63
64
|
});
|
package/src/tools/definitions.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import {registry} from '../registry.js';
|
|
6
|
+
import {ensureSkillTool} from '../agent/skills.js';
|
|
6
7
|
|
|
7
8
|
export interface ToolDef {
|
|
8
9
|
type: 'function';
|
|
@@ -34,9 +35,13 @@ export function getExtensionTools(): readonly ToolDef[] {
|
|
|
34
35
|
/**
|
|
35
36
|
* Get all tools — core tools plus registered extension tools, plus any
|
|
36
37
|
* explicitly supplied ones (kept for callers that aren't the registry).
|
|
38
|
+
*
|
|
39
|
+
* `load_skill` is appended here (rather than sitting in `CORE_TOOLS`) so it
|
|
40
|
+
* exists only while skill files do — no skills, no tool schema tokens.
|
|
37
41
|
*/
|
|
38
42
|
export function getAllTools(extra: ToolDef[] = []): ToolDef[] {
|
|
39
|
-
|
|
43
|
+
const skillTool = ensureSkillTool();
|
|
44
|
+
return [...CORE_TOOLS, ...registry.extensionTools, ...extra, ...(skillTool ? [skillTool] : [])];
|
|
40
45
|
}
|
|
41
46
|
|
|
42
47
|
export const CORE_TOOLS: ToolDef[] = [
|
|
@@ -75,13 +80,22 @@ export const CORE_TOOLS: ToolDef[] = [
|
|
|
75
80
|
type: 'function',
|
|
76
81
|
function: {
|
|
77
82
|
name: 'edit_file',
|
|
78
|
-
description:
|
|
83
|
+
description:
|
|
84
|
+
'Replace exact string in file; structural pattern+rewrite fallback when exact text unknown.',
|
|
79
85
|
parameters: {
|
|
80
86
|
type: 'object',
|
|
81
87
|
properties: {
|
|
82
88
|
path: {type: 'string'},
|
|
83
89
|
old_string: {type: 'string'},
|
|
84
90
|
new_string: {type: 'string'},
|
|
91
|
+
pattern: {
|
|
92
|
+
type: 'string',
|
|
93
|
+
description: 'ast-grep pattern with $A captures; tried if old_string misses.',
|
|
94
|
+
},
|
|
95
|
+
rewrite: {
|
|
96
|
+
type: 'string',
|
|
97
|
+
description: 'Replacement built from $A captures; used with pattern.',
|
|
98
|
+
},
|
|
85
99
|
},
|
|
86
100
|
required: ['path', 'old_string', 'new_string'],
|
|
87
101
|
},
|