@anhlp/alp-runtime 0.0.1-beta.7 → 0.0.1-beta.9
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/dist/acp-transport.js +2 -0
- package/dist/antigravity-transport.d.ts +10 -2
- package/dist/antigravity-transport.js +26 -4
- package/dist/assignment-results.d.ts +5 -2
- package/dist/assignment-results.js +27 -15
- package/dist/catalog.js +2 -1
- package/dist/claude-transport.d.ts +33 -2
- package/dist/claude-transport.js +48 -9
- package/dist/contracts.d.ts +12 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +9 -2
- package/dist/language.d.ts +2 -0
- package/dist/language.js +6 -0
- package/dist/live.d.ts +2 -2
- package/dist/live.js +7 -2
- package/dist/model-catalog.d.ts +87 -1
- package/dist/model-catalog.js +151 -6
- package/dist/model-probes.d.ts +1 -1
- package/dist/model-probes.js +2 -2
- package/dist/recall.d.ts +2 -2
- package/dist/recall.js +4 -3
- package/dist/resolve.js +4 -4
- package/dist/runtime.js +243 -33
- package/dist/session-config.d.ts +75 -6
- package/dist/session-config.js +9 -5
- package/dist/session-state.d.ts +2 -0
- package/dist/skill-resources.d.ts +30 -0
- package/dist/skill-resources.js +55 -0
- package/dist/tools.d.ts +27 -1
- package/dist/tools.js +20 -1
- package/dist/write-error.d.ts +2 -0
- package/dist/write-error.js +10 -0
- package/package.json +4 -4
- package/src/acp-transport.ts +3 -0
- package/src/antigravity-transport.ts +39 -8
- package/src/assignment-results.ts +23 -15
- package/src/catalog.ts +3 -1
- package/src/claude-transport.ts +87 -10
- package/src/contracts.ts +12 -0
- package/src/index.ts +4 -3
- package/src/language.ts +10 -0
- package/src/live.ts +7 -3
- package/src/model-catalog.ts +156 -6
- package/src/model-probes.ts +2 -2
- package/src/recall.ts +4 -3
- package/src/resolve.ts +9 -5
- package/src/runtime.ts +255 -29
- package/src/session-config.ts +13 -5
- package/src/session-state.ts +2 -0
- package/src/skill-resources.ts +73 -0
- package/src/tools.ts +22 -1
- package/src/write-error.ts +4 -0
package/src/claude-transport.ts
CHANGED
|
@@ -11,18 +11,27 @@ import { inputLimitError, POUR_VARS, VAR_NAME, type InputLimits } from './input-
|
|
|
11
11
|
import { claudeToolDetail, resultText } from './tool-detail.js';
|
|
12
12
|
import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from '@anhlp/alp-core/tasks';
|
|
13
13
|
import { commandDecision } from '@anhlp/alp-core/permissions';
|
|
14
|
+
import { isScript, nativeDaemon, nodeExecutable } from '@anhlp/alp-core/packaged';
|
|
14
15
|
|
|
15
16
|
// Keep the Claude SDK behind the runtime boundary. Paseo inspects static
|
|
16
17
|
// imports while compiling plugin entrypoints, including their declaration
|
|
17
18
|
// graph; the SDK is a daemon-only optional runtime dependency.
|
|
19
|
+
// The native alpd (t-81b0.9) carries the SDK inside its executable: there is no node_modules to import
|
|
20
|
+
// it from by name, so its entry registers it.
|
|
18
21
|
const CLAUDE_SDK = ['@anthropic-ai', 'claude-agent-sdk'].join('/');
|
|
19
|
-
const claudeSdk = (): Promise<any> => import(CLAUDE_SDK);
|
|
22
|
+
const claudeSdk = (): Promise<any> => nativeDaemon()?.modules.claudeAgentSdk?.() ?? import(CLAUDE_SDK);
|
|
23
|
+
/**
|
|
24
|
+
* A JavaScript `claude` (a test's fake, an npm install's cli.js) runs under Node. The SDK would pick
|
|
25
|
+
* `bun` inside the native alpd, so name the Node there.
|
|
26
|
+
*/
|
|
27
|
+
// The SDK treats .js/.mjs/.cjs/.ts/.tsx/.jsx as scripts.
|
|
28
|
+
const scriptExecutable = (command: string): { executable?: any } => nativeDaemon() && (isScript(command) || /\.(ts|tsx|jsx)$/i.test(command)) ? { executable: nodeExecutable() } : {};
|
|
20
29
|
|
|
21
30
|
type SDKUserMessage = any;
|
|
22
31
|
type SDKMessage = any;
|
|
23
32
|
type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
|
|
24
33
|
supportedModels(): Promise<Array<{ value: string; displayName: string; description: string; supportedEffortLevels?: string[] }>>;
|
|
25
|
-
supportedCommands(): Promise<Array<{ name: string; description: string; argumentHint?: string }>>;
|
|
34
|
+
supportedCommands(): Promise<Array<{ name: string; description: string; argumentHint?: string; builtin?: boolean }>>;
|
|
26
35
|
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(options: { skipBehaviors: boolean }): Promise<any>;
|
|
27
36
|
getContextUsage(options: { detail: 'summary' | 'full' }): Promise<any>;
|
|
28
37
|
interrupt(): Promise<unknown>;
|
|
@@ -31,7 +40,17 @@ type ClaudeQuery = AsyncGenerator<SDKMessage, void> & {
|
|
|
31
40
|
initializationResult?(): Promise<unknown>;
|
|
32
41
|
};
|
|
33
42
|
|
|
34
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
* A field whose size is checked before zod walks it; its JSON Schema is the inner schema's
|
|
45
|
+
* (input-limits.ts).
|
|
46
|
+
*
|
|
47
|
+
* Needed for any field zod's own cap does not protect. zod's GHSA-mrhx-c7xc-m3w5 fix (4.6.6) refuses
|
|
48
|
+
* a collection over its `.max()` before reading an element for `array`, `map` and `set` — and for
|
|
49
|
+
* NOTHING ELSE. `z.record` is NOT covered: a capped record is still read element by element, one
|
|
50
|
+
* issue kept per failure (t-5294.4). So a limited record must go through `bounded` (as `vars` below
|
|
51
|
+
* does), and turning a capped `z.array` field into a `z.record` silently drops that protection.
|
|
52
|
+
* docs/alp/zod-advisory.md has the repository-wide survey.
|
|
53
|
+
*/
|
|
35
54
|
const bounded = <T extends z.ZodType>(schema: T, limits: InputLimits) => z.preprocess((value, ctx) => {
|
|
36
55
|
const error = inputLimitError(value, limits);
|
|
37
56
|
if (error) ctx.addIssue({ code: 'custom', message: error });
|
|
@@ -91,6 +110,11 @@ export const toolShapes: Record<string, Record<string, z.ZodType>> = {
|
|
|
91
110
|
replace: z.boolean().optional(),
|
|
92
111
|
requestId: z.string().min(1).max(100).optional(),
|
|
93
112
|
},
|
|
113
|
+
alp_skill_retire: {
|
|
114
|
+
name: z.string().min(1).max(64),
|
|
115
|
+
reason: z.string().min(1).max(300),
|
|
116
|
+
requestId: z.string().min(1).max(100).optional(),
|
|
117
|
+
},
|
|
94
118
|
alp_issue: {
|
|
95
119
|
action: z.enum(['search', 'create', 'comment']),
|
|
96
120
|
target: z.enum(['project', 'alp']),
|
|
@@ -223,8 +247,47 @@ type NativeConfig = {
|
|
|
223
247
|
|
|
224
248
|
/** The plugin name ALP's skills are loaded under, so Claude Code calls them alp:<name>. */
|
|
225
249
|
export const SKILL_PLUGIN = 'alp';
|
|
250
|
+
/** Claude's /clear and its aliases (supportedCommands reports `clear [reset, new]`): each starts a new conversation. */
|
|
251
|
+
const NEW_CONVERSATION_COMMANDS = ['clear', 'reset', 'new'];
|
|
252
|
+
const NEW_CONVERSATION = new RegExp(`^\\s*\\/(${NEW_CONVERSATION_COMMANDS.join('|')})(?:\\s|$)`);
|
|
226
253
|
/** Claude's own commands the composer does not offer: ALP does their work its own way (t-efa3). */
|
|
227
|
-
const ALP_HANDLED_COMMANDS = new Set([
|
|
254
|
+
const ALP_HANDLED_COMMANDS = new Set([...NEW_CONVERSATION_COMMANDS, 'compact', 'rewind']);
|
|
255
|
+
/** The aliases of /clear a command of the user's may take as its own name. */
|
|
256
|
+
const CLEAR_ALIASES = new Set(['reset', 'new']);
|
|
257
|
+
|
|
258
|
+
type ListedCommand = { name?: unknown; builtin?: unknown };
|
|
259
|
+
/**
|
|
260
|
+
* t-5ac5: the aliases of /clear (new, reset) that, in this listing, run a command of the user's,
|
|
261
|
+
* project, plugin or MCP server rather than Claude's /clear. The SDK marks Claude's own rows
|
|
262
|
+
* `builtin: true`; a marked row wins its name, and an alias runs a command that has it as its name
|
|
263
|
+
* (SlashCommand.builtin). So /new is the user's when an unmarked row is named new and no marked row is.
|
|
264
|
+
* A listing without the marker (an older Claude Code) cannot tell the two apart: nothing is the
|
|
265
|
+
* user's then, and ALP keeps refusing /new and /reset, since letting Claude's /clear through loses the
|
|
266
|
+
* conversation while refusing a custom command only costs the user its name. /clear itself is always
|
|
267
|
+
* Claude's: a marked row is named clear.
|
|
268
|
+
*/
|
|
269
|
+
export function customClearAliases(listed: ReadonlyArray<ListedCommand> | undefined): Set<string> {
|
|
270
|
+
const rows = Array.isArray(listed) ? listed : [];
|
|
271
|
+
if (!rows.some(row => typeof row?.builtin === 'boolean')) return new Set();
|
|
272
|
+
const builtin = new Set(rows.filter(row => row?.builtin === true).map(row => row.name));
|
|
273
|
+
return new Set(rows.filter(row => row?.builtin !== true && typeof row?.name === 'string' && CLEAR_ALIASES.has(row.name) && !builtin.has(row.name)).map(row => row.name as string));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* t-e906: Claude's /clear moves it to a new conversation under a new session id while ALP keeps the
|
|
278
|
+
* old thread, so resume, fork and rewind would point at the conversation from before. ALP refuses it
|
|
279
|
+
* rather than follow: its timeline, turn ids and rewinds belong to the old conversation. /reset and /new are
|
|
280
|
+
* the same command, unless the session lists a command of the user's under that name (`custom`,
|
|
281
|
+
* from customClearAliases).
|
|
282
|
+
*/
|
|
283
|
+
export function nativeCommandRefusal(runtimeKind: string, content: ReadonlyArray<{ type: string; text?: string }>, custom?: ReadonlySet<string>) {
|
|
284
|
+
if (runtimeKind !== 'claude') return undefined;
|
|
285
|
+
// The text Claude gets: every text part, joined as startPrompt joins them.
|
|
286
|
+
const typed = content.filter(part => part.type === 'text').map(part => part.text ?? '').join('\n');
|
|
287
|
+
const named = NEW_CONVERSATION.exec(typed)?.[1];
|
|
288
|
+
if (!named || custom?.has(named)) return undefined;
|
|
289
|
+
return 'ALP does not pass /clear (or /new, /reset) to Claude: Claude would start a new conversation that this session does not follow. Start a new session in ALP for a fresh conversation, or compact this one (alp compact, or Compact in the app).';
|
|
290
|
+
}
|
|
228
291
|
|
|
229
292
|
/**
|
|
230
293
|
* A Claude Code plugin in `directory` holding the given skills, linked to their own
|
|
@@ -465,24 +528,35 @@ export class ClaudeTransport {
|
|
|
465
528
|
}
|
|
466
529
|
/**
|
|
467
530
|
* Claude's slash commands, skills included, for the composer (t-f628); none before the session starts.
|
|
468
|
-
* Not the ones whose work ALP does itself (t-efa3): /clear moves Claude to a new conversation ALP does not
|
|
469
|
-
* follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline.
|
|
531
|
+
* Not the ones whose work ALP does itself (t-efa3): /clear (/reset, /new) moves Claude to a new conversation ALP does not
|
|
532
|
+
* follow, and /compact and /rewind skip ALP's checkpoint and its rewind of the timeline. A command of the user's
|
|
533
|
+
* named new or reset is offered (t-5ac5, customClearAliases); one named clear, compact or rewind never runs, Claude's wins.
|
|
470
534
|
*/
|
|
471
535
|
async commands() {
|
|
472
|
-
const listed =
|
|
473
|
-
|
|
536
|
+
const listed = await this.listCommands();
|
|
537
|
+
const custom = customClearAliases(listed);
|
|
538
|
+
return (Array.isArray(listed) ? listed : []).filter(command => typeof command?.name === 'string' && command.name
|
|
539
|
+
&& (!ALP_HANDLED_COMMANDS.has(command.name) || (command.builtin !== true && custom.has(command.name)))).map(command => ({
|
|
474
540
|
name: command.name, description: typeof command.description === 'string' ? command.description : '',
|
|
475
541
|
...(command.argumentHint ? { argumentHint: command.argumentHint } : {}),
|
|
476
542
|
kind: command.name.startsWith(`${SKILL_PLUGIN}:`) ? 'skill' as const : 'command' as const,
|
|
477
543
|
}));
|
|
478
544
|
}
|
|
545
|
+
/** The aliases of /clear that run a command of the user's, as the last listing said (t-5ac5); none before one. */
|
|
546
|
+
customCommands(): ReadonlySet<string> { return this.customAliases; }
|
|
547
|
+
private customAliases: ReadonlySet<string> = new Set();
|
|
548
|
+
private async listCommands() {
|
|
549
|
+
const listed = this.query ? await optionalRead(async () => this.query!.supportedCommands(), 10_000) : undefined;
|
|
550
|
+
if (Array.isArray(listed)) this.customAliases = customClearAliases(listed);
|
|
551
|
+
return listed;
|
|
552
|
+
}
|
|
479
553
|
async initialize() {}
|
|
480
554
|
|
|
481
555
|
/** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
|
|
482
556
|
async probeModels(signal?: AbortSignal) {
|
|
483
557
|
const { query } = await claudeSdk();
|
|
484
558
|
if (signal?.aborted) throw new Error('aborted');
|
|
485
|
-
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
559
|
+
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command, ...scriptExecutable(this.command) } }) as ClaudeQuery;
|
|
486
560
|
// A probe that outlives its bound is closed, so a hanging Claude process never stays behind.
|
|
487
561
|
const stop = () => probe.close();
|
|
488
562
|
signal?.addEventListener('abort', stop);
|
|
@@ -499,7 +573,7 @@ export class ClaudeTransport {
|
|
|
499
573
|
private async probeUsage() {
|
|
500
574
|
if (this.closed) return undefined;
|
|
501
575
|
const { query } = await claudeSdk();
|
|
502
|
-
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
576
|
+
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command, ...scriptExecutable(this.command) } }) as ClaudeQuery;
|
|
503
577
|
try {
|
|
504
578
|
return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
|
|
505
579
|
} finally {
|
|
@@ -747,6 +821,7 @@ export class ClaudeTransport {
|
|
|
747
821
|
...(from ? { resume: from.resume, ...(from.fork ? { forkSession: true, sessionId: this.threadId } : {}), ...(from.at ? { resumeSessionAt: from.at } : {}) } : { sessionId: this.threadId }),
|
|
748
822
|
// Explicit native path avoids SDK optional binaries inside Electron app.asar.
|
|
749
823
|
pathToClaudeCodeExecutable: this.command,
|
|
824
|
+
...scriptExecutable(this.command),
|
|
750
825
|
};
|
|
751
826
|
|
|
752
827
|
this.bootFailure = new Promise<never>((_, reject) => { this.rejectBoot = reject; });
|
|
@@ -754,6 +829,8 @@ export class ClaudeTransport {
|
|
|
754
829
|
this.query = query({ prompt: this.input, options }) as ClaudeQuery;
|
|
755
830
|
this.pump = this.consume(this.query).catch((error) => this.fail(error));
|
|
756
831
|
void this.measureContext();
|
|
832
|
+
// The listing says which of /new and /reset are the user's own, before the first prompt is checked.
|
|
833
|
+
void this.listCommands();
|
|
757
834
|
}
|
|
758
835
|
|
|
759
836
|
/** Reads the window and the compaction threshold Claude resolved for this session, before any turn. */
|
package/src/contracts.ts
CHANGED
|
@@ -18,6 +18,8 @@ export type RuntimeTransport = {
|
|
|
18
18
|
orchestrationContext?: () => Promise<unknown>;
|
|
19
19
|
/** The runtime's own slash commands and skills for the composer (t-f628); omitted, the runtime offers none. */
|
|
20
20
|
commands?: () => Promise<RuntimeCommand[]>;
|
|
21
|
+
/** Claude: the aliases of /clear (new, reset) that run a command of the user's, so they are not refused (t-5ac5). */
|
|
22
|
+
customCommands?: () => ReadonlySet<string>;
|
|
21
23
|
onNotification(listener: (method: string, params: any) => void): void;
|
|
22
24
|
onFailure(listener: (error: unknown) => void): void;
|
|
23
25
|
close(): Promise<void>;
|
|
@@ -109,6 +111,14 @@ export type RuntimeOptions = {
|
|
|
109
111
|
/** Where running assignments are kept, so the next alpd continues them (ALPD §31). Omitted keeps them in memory. */
|
|
110
112
|
liveFile?: string;
|
|
111
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Told of every failed write to pauseFile, liveFile, recallFile and assignmentResultFile, as it
|
|
116
|
+
* happens, so the host's disk guard pauses work on a full disk at once (t-e80a). Each write still
|
|
117
|
+
* fails as before: pauses and recall go on in memory, live entries are logged, and result
|
|
118
|
+
* ownership is refused to its caller.
|
|
119
|
+
*/
|
|
120
|
+
onWriteError?: (error: unknown) => void;
|
|
121
|
+
|
|
112
122
|
/** False parks assignments an earlier alpd left running until the user runs alp resume. Default true: they continue. */
|
|
113
123
|
recoveryResume?: boolean;
|
|
114
124
|
|
|
@@ -134,6 +144,8 @@ export type AlpRuntime = {
|
|
|
134
144
|
bindAttachments?: (reader: AttachmentReader | undefined) => void;
|
|
135
145
|
/** Whether this live session's runtime takes `{ type: 'attachment' }` parts (RuntimeAttachment) now. */
|
|
136
146
|
takesAttachments?: (sessionId: string) => boolean;
|
|
147
|
+
/** Why this live session's runtime refuses this prompt before it is sent (t-e906), or undefined. */
|
|
148
|
+
refusesPrompt?: (sessionId: string, content: PromptContent) => string | undefined;
|
|
137
149
|
/** Removes the staged copy of an attachment alpd no longer keeps. */
|
|
138
150
|
dropAttachment?: (attachmentId: string) => Promise<void>;
|
|
139
151
|
onEvent(listener: (envelope: Envelope) => void): () => void;
|
package/src/index.ts
CHANGED
|
@@ -5,11 +5,12 @@ export { ConversationError } from './contracts.js';
|
|
|
5
5
|
export type { RuntimeCommand, BranchRequest, ConversationErrorReason, NativeBase, NativeBinding, ConfigureChanges, ConfigureResult, ConfigurePreview, EffectiveConfig } from './contracts.js';
|
|
6
6
|
export type { AlpEvent, AlpError, Envelope, SessionSnapshot, TimelineItem, TurnOrigin, AssignmentSnapshot, UserQuestion, TreeStatus, SessionState } from './events.js';
|
|
7
7
|
export { resolveSession, InstructionsAdapter, skillDescription } from './resolve.js';
|
|
8
|
+
export { resourceUses, pathActions } from './skill-resources.js';
|
|
8
9
|
export type { SessionSpec, HostMcpServer, ResolvedSession, RuntimeKind } from './resolve.js';
|
|
9
10
|
export { DEFAULT_MODEL, DEFAULT_CLAUDE_MODEL, entries as catalogEntries, models, modes, thinkingOptions, thinkingOptionsFor } from './catalog.js';
|
|
10
11
|
export type { CatalogEntry } from './catalog.js';
|
|
11
|
-
export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
|
|
12
|
-
export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe } from './model-catalog.js';
|
|
12
|
+
export { ModelCatalog, mergeCatalog, liveFromContext, feedCatalog, feedAcpSession, acpSessionModels, setActiveCatalog, activeCatalog, POLICY as CATALOG_POLICY, REFRESH_MS as CATALOG_REFRESH_MS } from './model-catalog.js';
|
|
13
|
+
export type { CatalogSnapshot, CatalogRuntime, LiveModel, Probe as CatalogProbe, AcpProviderConfig, AcpProbe, AcpRow, AcpState } from './model-catalog.js';
|
|
13
14
|
export { liveProbes, codexProbe, claudeProbe, antigravityProbe, parseAgyModels } from './model-probes.js';
|
|
14
15
|
export { CodexTransport } from './transport.js';
|
|
15
16
|
export { ATTACHMENT_HEADER, ATTACHMENT_ROUTES, attachmentStageDir, createAttachmentStager, stagingExposure } from './attachments.js';
|
|
@@ -19,7 +20,7 @@ export { AcpTransport, acpDecision, acpEnv, acpPermission } from './acp-transpor
|
|
|
19
20
|
export type { AcpProvider } from './acp-transport.js';
|
|
20
21
|
export { AntigravityTransport } from './antigravity-transport.js';
|
|
21
22
|
export type { AntigravityProvider } from './antigravity-transport.js';
|
|
22
|
-
export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
|
|
23
|
+
export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, customClearAliases, nativeCommandRefusal, skillPlugin, SKILL_PLUGIN, toolShapes as claudeToolShapes } from './claude-transport.js';
|
|
23
24
|
export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
|
|
24
25
|
export type { MailEvent, MailKind } from './mailbox.js';
|
|
25
26
|
export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
|
package/src/language.ts
CHANGED
|
@@ -18,6 +18,10 @@ const en = {
|
|
|
18
18
|
`${agent} wants to ${create ? `open an issue in ${where}` : `comment on issue #${issue} in ${where}`}. ` +
|
|
19
19
|
'It is posted with your GitHub account, and anyone who can see the repository can read it.',
|
|
20
20
|
issueTitle: 'Title',
|
|
21
|
+
skillRetire: (agent: string, name: string, file: string, retired: string, roles: string, users: string, reason: string) =>
|
|
22
|
+
`${agent} proposes to retire the skill ${name} (${file}): ${reason}\n` +
|
|
23
|
+
`Approve to move it to ${retired}, where it is kept and can be restored, and remove it from ${roles ? `the roles that have it: ${roles}` : 'role-skills.json (no role has it)'}. Nothing else changes.` +
|
|
24
|
+
(users ? ` It is still named in agent.json by ${users}; it is not retired until they stop naming it.` : ''),
|
|
21
25
|
lessonCurate: (agent: string, changes: string) =>
|
|
22
26
|
`${agent} proposes to curate the lessons files. Approve to apply every change below at once; nothing else changes.\n\n${changes}`,
|
|
23
27
|
lessonRemove: 'Remove',
|
|
@@ -38,6 +42,7 @@ const en = {
|
|
|
38
42
|
limitReached: (runtime: string, resetsAt: string | undefined, other: string | undefined, autoResume: boolean, kind: string) =>
|
|
39
43
|
`${runtime} usage limit reached${resetsAt ? `; it resets ${resetsAt}` : ''}. ALP paused delegation to ${runtime} agents and parked their assignments${other ? `; ${other} agents keep working` : ''}. ${autoResume ? `ALP asks ${runtime} every minute and resumes it as soon as the limit lifts.` : `ALP asks ${runtime} every minute and tells you when the limit lifts; then run alp resume ${kind}.`}`,
|
|
40
44
|
limitLifted: (runtime: string, kind: string) => `${runtime} says its usage limit has lifted. Run alp resume ${kind} to continue its work.`,
|
|
45
|
+
compacting: () => 'Compacting main\'s context: main writes a checkpoint first.',
|
|
41
46
|
compacted: (native: boolean) => `Main's context was compacted${native ? '' : ' into a fresh conversation'}; it keeps its checkpoint and carries on.`,
|
|
42
47
|
compactFailed: (reason: string) => `Compacting main's context failed (${reason}); ALP tries again later.`,
|
|
43
48
|
usageWarning: (runtime: string, used: string, resetsAt: string | undefined) => `${runtime} has used ${used} of a usage window${resetsAt ? ` that resets ${resetsAt}` : ''}.`,
|
|
@@ -67,6 +72,10 @@ const vi: Words = {
|
|
|
67
72
|
`${agent} muốn ${create ? `mở một issue trong ${where}` : `bình luận vào issue #${issue} trong ${where}`}. ` +
|
|
68
73
|
'Nội dung được đăng bằng tài khoản GitHub của bạn, ai xem được repository đều đọc được.',
|
|
69
74
|
issueTitle: 'Tiêu đề',
|
|
75
|
+
skillRetire: (agent, name, file, retired, roles, users, reason) =>
|
|
76
|
+
`${agent} đề xuất cho skill ${name} (${file}) nghỉ: ${reason}\n` +
|
|
77
|
+
`Duyệt để chuyển nó sang ${retired}, nơi nó vẫn được giữ và có thể khôi phục, và bỏ nó khỏi ${roles ? `các vai đang dùng: ${roles}` : 'role-skills.json (không vai nào dùng)'}. Không thay đổi gì khác.` +
|
|
78
|
+
(users ? ` Nó vẫn được nêu trong agent.json của ${users}; nó chỉ được cho nghỉ khi các agent đó thôi nêu nó.` : ''),
|
|
70
79
|
lessonCurate: (agent, changes) =>
|
|
71
80
|
`${agent} đề xuất rà soát file bài học. Duyệt để áp dụng cùng lúc mọi thay đổi dưới đây; không thay đổi gì khác.\n\n${changes}`,
|
|
72
81
|
lessonRemove: 'Bỏ',
|
|
@@ -87,6 +96,7 @@ const vi: Words = {
|
|
|
87
96
|
limitReached: (runtime, resetsAt, other, autoResume, kind) =>
|
|
88
97
|
`${runtime} đã hết hạn mức sử dụng${resetsAt ? `; hạn mức đặt lại lúc ${resetsAt}` : ''}. ALP tạm dừng giao việc cho các agent ${runtime} và tạm giữ việc của chúng${other ? `; các agent ${other} vẫn làm tiếp` : ''}. ${autoResume ? `ALP hỏi ${runtime} mỗi phút và tự chạy lại ngay khi có hạn mức.` : `ALP hỏi ${runtime} mỗi phút và báo khi có hạn mức trở lại; khi đó chạy alp resume ${kind}.`}`,
|
|
89
98
|
limitLifted: (runtime, kind) => `${runtime} báo đã có hạn mức trở lại. Chạy alp resume ${kind} để làm tiếp việc của nó.`,
|
|
99
|
+
compacting: () => 'Đang compact context của main: main viết checkpoint trước.',
|
|
90
100
|
compacted: native => `Context của main đã được compact${native ? '' : ' sang một cuộc hội thoại mới'}; main giữ checkpoint và làm tiếp.`,
|
|
91
101
|
compactFailed: reason => `Compact context của main thất bại (${reason}); ALP sẽ thử lại sau.`,
|
|
92
102
|
usageWarning: (runtime, used, resetsAt) => `${runtime} đã dùng ${used} hạn mức của kỳ này${resetsAt ? `, kỳ đặt lại lúc ${resetsAt}` : ''}.`,
|
package/src/live.ts
CHANGED
|
@@ -5,6 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { createLogger } from '@anhlp/alp-core/log';
|
|
6
6
|
import type { RuntimeKind, SessionSpec } from './resolve.js';
|
|
7
7
|
import type { Worktree } from './workspace.js';
|
|
8
|
+
import { tell } from './write-error.js';
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* Assignments that are running, kept on disk so the next alpd can continue them
|
|
@@ -49,8 +50,8 @@ const valid = (entry: any): entry is LiveEntry => !!entry && typeof entry === 'o
|
|
|
49
50
|
['assignmentId', 'rootId', 'parentId', 'agent', 'project', 'runtime', 'model', 'threadId', 'mode', 'isolation', 'epoch'].every(key => typeof entry[key] === 'string') &&
|
|
50
51
|
Array.isArray(entry.ancestry) && !!entry.spec && typeof entry.spec === 'object' && typeof entry.startedAt === 'number';
|
|
51
52
|
|
|
52
|
-
/** The book of running assignments, in `file` when given, else in memory. */
|
|
53
|
-
export function createLiveBook(file?: string) {
|
|
53
|
+
/** The book of running assignments, in `file` when given, else in memory; `onError` hears of each failed write. */
|
|
54
|
+
export function createLiveBook(file?: string, onError: (error: unknown) => void = () => {}) {
|
|
54
55
|
let entries: LiveEntry[] = [];
|
|
55
56
|
if (file) {
|
|
56
57
|
try { entries = (JSON.parse(readFileSync(file, 'utf8')) as unknown[]).filter(valid); } catch {}
|
|
@@ -64,7 +65,10 @@ export function createLiveBook(file?: string) {
|
|
|
64
65
|
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
65
66
|
await writeFile(temporary, body, { mode: 0o600 });
|
|
66
67
|
await rename(temporary, file);
|
|
67
|
-
}).catch(error =>
|
|
68
|
+
}).catch(error => {
|
|
69
|
+
tell(onError, error);
|
|
70
|
+
createLogger({ component: 'runtime' }).error('could not save the live assignments', { code: 'ALP_PERSISTENCE_WRITE_FAILED', operation: 'live assignments', error });
|
|
71
|
+
});
|
|
68
72
|
return writes;
|
|
69
73
|
};
|
|
70
74
|
return {
|
package/src/model-catalog.ts
CHANGED
|
@@ -13,8 +13,18 @@ export type CatalogRuntime = 'codex' | 'claude' | 'antigravity';
|
|
|
13
13
|
/** A model as a provider reports it. */
|
|
14
14
|
export type LiveModel = { id: string; label?: string; description?: string; efforts?: string[]; effort?: string };
|
|
15
15
|
export type ProviderState = { status: 'ok' | 'failed' | 'static'; fetchedAt?: string; error?: string; models: LiveModel[] };
|
|
16
|
-
|
|
16
|
+
/** What ALP learned of an ACP provider's models (t-d0b0): nothing until a session or an explicit probe tells it. */
|
|
17
|
+
export type AcpStatus = 'unprobed' | 'ok' | 'failed';
|
|
18
|
+
export type AcpState = { status: AcpStatus; fetchedAt?: string; error?: string; models: LiveModel[] };
|
|
19
|
+
export type CatalogSnapshot = { fetchedAt?: string; providers: Partial<Record<CatalogRuntime, ProviderState>>; acp?: Record<string, AcpState> };
|
|
17
20
|
export type Probe = (signal: AbortSignal) => Promise<LiveModel[]>;
|
|
21
|
+
/** A provider of the library (providers/<id>.json), as loadProvider reads it. */
|
|
22
|
+
export type AcpProviderConfig = { id: string; kind?: string; label?: string; description?: string; enabled?: boolean;
|
|
23
|
+
models?: Array<{ id: string; label?: string; description?: string }>; additionalModels?: Array<{ id: string; label?: string; description?: string }> };
|
|
24
|
+
export type AcpProbe = (provider: AcpProviderConfig, signal: AbortSignal) => Promise<LiveModel[]>;
|
|
25
|
+
/** An ACP row of the catalog: `acp:<provider>` (the agent's own default) and `acp:<provider>/<model>`. */
|
|
26
|
+
export type AcpRow = { runtime: 'acp'; provider: string; id: string; label: string; description: string; efforts: string[];
|
|
27
|
+
source: 'configured' | 'live'; enabled: boolean; status: AcpStatus };
|
|
18
28
|
|
|
19
29
|
const RUNTIMES: CatalogRuntime[] = ['codex', 'claude', 'antigravity'];
|
|
20
30
|
export const REFRESH_MS = 6 * 60 * 60 * 1000;
|
|
@@ -54,7 +64,20 @@ function sanitize(value: any): CatalogSnapshot {
|
|
|
54
64
|
if (!state || typeof state !== 'object') continue;
|
|
55
65
|
providers[runtime] = { status: state.status === 'ok' ? 'ok' : 'failed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), models: sanitizeModels(state.models) };
|
|
56
66
|
}
|
|
57
|
-
|
|
67
|
+
const acp: Record<string, AcpState> = {};
|
|
68
|
+
if (value?.acp && typeof value.acp === 'object') for (const [id, state] of Object.entries<any>(value.acp)) {
|
|
69
|
+
if (!/^[\w.-]+$/.test(id) || !state || typeof state !== 'object') continue;
|
|
70
|
+
acp[id] = { status: state.status === 'ok' ? 'ok' : state.status === 'failed' ? 'failed' : 'unprobed', ...(typeof state.fetchedAt === 'string' ? { fetchedAt: state.fetchedAt } : {}), ...(typeof state.error === 'string' ? { error: state.error } : {}), models: sanitizeModels(state.models) };
|
|
71
|
+
}
|
|
72
|
+
return { ...(typeof value?.fetchedAt === 'string' ? { fetchedAt: value.fetchedAt } : {}), providers, ...(Object.keys(acp).length ? { acp } : {}) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The models a `session/new` answer offers (ACP `models.availableModels`, or a model select config option). */
|
|
76
|
+
export function acpSessionModels(result: any): LiveModel[] {
|
|
77
|
+
const config = Array.isArray(result?.configOptions) ? result.configOptions.find((option: any) => option?.category === 'model' && option?.type === 'select') : undefined;
|
|
78
|
+
const listed = Array.isArray(result?.models?.availableModels) ? result.models.availableModels
|
|
79
|
+
: config ? (config.options ?? []).flatMap((option: any) => option?.options ?? [option]).map((option: any) => ({ modelId: option?.value, name: option?.name, description: option?.description })) : [];
|
|
80
|
+
return sanitizeModels(listed.map((model: any) => ({ id: model?.modelId ?? model?.id, ...(typeof model?.name === 'string' && model.name ? { label: model.name } : {}), ...(typeof model?.description === 'string' && model.description ? { description: model.description } : {}) })));
|
|
58
81
|
}
|
|
59
82
|
|
|
60
83
|
type Listener = (snapshot: CatalogSnapshot, entries: CatalogEntry[]) => void;
|
|
@@ -66,8 +89,22 @@ export class ModelCatalog {
|
|
|
66
89
|
private timer?: NodeJS.Timeout;
|
|
67
90
|
private running?: Promise<CatalogSnapshot>;
|
|
68
91
|
private readonly file?: string;
|
|
92
|
+
private acpConfigs: AcpProviderConfig[] = [];
|
|
93
|
+
private acpRunning?: Promise<CatalogSnapshot>;
|
|
94
|
+
private acpError?: string;
|
|
95
|
+
private acpLearning = new Map<string, Set<string>>();
|
|
96
|
+
/** Cache writes under way: stop() waits for them, so whoever stopped the catalog may remove its home. */
|
|
97
|
+
private writes = new Set<Promise<void>>();
|
|
98
|
+
/** Set once stop() has drained: a late answer (a session's models, an ingest) still updates memory but writes nothing. */
|
|
99
|
+
private stopped = false;
|
|
69
100
|
|
|
70
|
-
|
|
101
|
+
/**
|
|
102
|
+
* ACP providers (t-d0b0) come from `acpProviders` (the library's providers/<id>.json) without starting
|
|
103
|
+
* them; their models are learned from sessions (learnAcp) and probed (acpProbe) only by refreshAcp,
|
|
104
|
+
* which alpd calls on catalog.refresh and when the user enables a provider. Never at start or on the timer.
|
|
105
|
+
*/
|
|
106
|
+
constructor(private readonly options: { home?: string; probes: Partial<Record<CatalogRuntime, Probe>>; timeoutMs?: number; refreshMs?: number; now?: () => Date; apply?: boolean;
|
|
107
|
+
acpProviders?: () => Promise<AcpProviderConfig[] | { providers: AcpProviderConfig[]; error?: string }>; acpProbe?: AcpProbe }) {
|
|
71
108
|
this.file = options.home ? catalogCacheFile(options.home) : undefined;
|
|
72
109
|
}
|
|
73
110
|
|
|
@@ -77,12 +114,27 @@ export class ModelCatalog {
|
|
|
77
114
|
|
|
78
115
|
/** Loads the cache, then refreshes in the background and every refreshMs. Never blocks on a provider. */
|
|
79
116
|
async start() {
|
|
117
|
+
this.stopped = false;
|
|
80
118
|
await this.load();
|
|
119
|
+
await this.loadAcp().catch(() => {});
|
|
81
120
|
void this.refresh().catch(() => {});
|
|
82
121
|
const every = this.options.refreshMs ?? REFRESH_MS;
|
|
83
122
|
if (every > 0) { this.timer = setInterval(() => { void this.refresh().catch(() => {}); }, every); this.timer.unref?.(); }
|
|
84
123
|
}
|
|
85
|
-
|
|
124
|
+
/**
|
|
125
|
+
* Stops the timer and the listeners, then waits for what already started (a background refresh, a
|
|
126
|
+
* refreshAcp a saved provider asked for, a learned model's cache write) to finish writing the cache
|
|
127
|
+
* (t-5294.2). After that it writes the cache no more, until start() again. A caller that only stops may
|
|
128
|
+
* ignore the promise; one that removes the home awaits it.
|
|
129
|
+
*/
|
|
130
|
+
async stop() {
|
|
131
|
+
if (this.timer) clearInterval(this.timer);
|
|
132
|
+
this.timer = undefined;
|
|
133
|
+
this.listeners.clear();
|
|
134
|
+
// A refreshAcp queued behind a running one starts when it ends: wait until nothing runs.
|
|
135
|
+
while (this.running || this.acpRunning || this.writes.size) await Promise.allSettled([this.running, this.acpRunning, ...this.writes]);
|
|
136
|
+
this.stopped = true;
|
|
137
|
+
}
|
|
86
138
|
|
|
87
139
|
async load() {
|
|
88
140
|
if (!this.file) return;
|
|
@@ -131,13 +183,106 @@ export class ModelCatalog {
|
|
|
131
183
|
return true;
|
|
132
184
|
}
|
|
133
185
|
|
|
186
|
+
/** Rereads the ACP providers' files; starts none of them. */
|
|
187
|
+
async loadAcp() {
|
|
188
|
+
if (!this.options.acpProviders) return;
|
|
189
|
+
// A listing that fails (an unreadable providers directory) keeps the rows ALP had and records why.
|
|
190
|
+
try {
|
|
191
|
+
const loaded = await this.options.acpProviders();
|
|
192
|
+
this.acpConfigs = (Array.isArray(loaded) ? loaded : loaded.providers).filter(provider => provider.kind !== 'antigravity');
|
|
193
|
+
this.acpError = Array.isArray(loaded) ? undefined : loaded.error;
|
|
194
|
+
} catch (error) { this.acpError = error instanceof Error ? error.message : String(error); }
|
|
195
|
+
}
|
|
196
|
+
/** Why the last reading of the ACP providers failed, if it did. */
|
|
197
|
+
acpLoadError(): string | undefined { return this.acpError; }
|
|
198
|
+
|
|
199
|
+
/** The ACP rows: each provider's default, then its models (the file's `models` replace learned ones; `additionalModels` add). */
|
|
200
|
+
acpRows(): AcpRow[] {
|
|
201
|
+
const rows: AcpRow[] = [];
|
|
202
|
+
for (const provider of this.acpConfigs) {
|
|
203
|
+
const state = this.snapshot.acp?.[provider.id];
|
|
204
|
+
const status = state?.status ?? 'unprobed';
|
|
205
|
+
const enabled = provider.enabled !== false;
|
|
206
|
+
const label = provider.label ?? provider.id;
|
|
207
|
+
const row = (id: string, text: string, description: string, source: AcpRow['source']): AcpRow => ({ runtime: 'acp', provider: provider.id, id, label: text, description, efforts: [], source, enabled, status });
|
|
208
|
+
rows.push(row(provider.id, `${label} · agent default`, provider.description ?? '', 'configured'));
|
|
209
|
+
const seen = new Set<string>();
|
|
210
|
+
const add = (models: Array<{ id: string; label?: string; description?: string }>, source: AcpRow['source']) => {
|
|
211
|
+
for (const model of models) if (!seen.has(model.id)) { seen.add(model.id); rows.push(row(`${provider.id}/${model.id}`, `${label} · ${model.label ?? model.id}`, model.description ?? '', source)); }
|
|
212
|
+
};
|
|
213
|
+
add(provider.models ?? state?.models ?? [], provider.models ? 'configured' : 'live');
|
|
214
|
+
add(provider.additionalModels ?? [], 'configured');
|
|
215
|
+
}
|
|
216
|
+
return rows;
|
|
217
|
+
}
|
|
218
|
+
/** The models ALP learned or probed for one ACP provider. */
|
|
219
|
+
acpModels(provider: string): LiveModel[] { return this.snapshot.acp?.[provider]?.models ?? []; }
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* A list an ACP session's `session/new` reported (t-d0b0). Additive, as ingest: it never removes a model
|
|
223
|
+
* a probe answered; a list with nothing new changes nothing.
|
|
224
|
+
*/
|
|
225
|
+
async learnAcp(provider: string, models: LiveModel[]) {
|
|
226
|
+
if (!/^[\w.-]+$/.test(provider)) return false;
|
|
227
|
+
const reported = sanitizeModels(models);
|
|
228
|
+
for (const model of reported) this.acpLearning.get(provider)?.add(model.id);
|
|
229
|
+
const prior = this.snapshot.acp?.[provider];
|
|
230
|
+
const known = new Set((prior?.models ?? []).map(model => model.id));
|
|
231
|
+
const added = reported.filter(model => !known.has(model.id));
|
|
232
|
+
if (!added.length) return false;
|
|
233
|
+
this.snapshot.acp = { ...this.snapshot.acp, [provider]: { status: 'ok', fetchedAt: (this.options.now?.() ?? new Date()).toISOString(), models: [...(prior?.models ?? []), ...added] } };
|
|
234
|
+
await this.publish(true);
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Starts each enabled ACP provider (or the named ones) once to read its models: only on an explicit
|
|
240
|
+
* catalog.refresh or when the user enables a provider. A failure keeps what ALP knew and records why.
|
|
241
|
+
*/
|
|
242
|
+
refreshAcp(ids?: string[]): Promise<CatalogSnapshot> {
|
|
243
|
+
if (this.acpRunning) return this.acpRunning.then(() => this.refreshAcp(ids));
|
|
244
|
+
this.acpRunning = (async () => {
|
|
245
|
+
await this.loadAcp();
|
|
246
|
+
const probe = this.options.acpProbe;
|
|
247
|
+
const targets = this.acpConfigs.filter(provider => provider.enabled !== false && (!ids || ids.includes(provider.id)));
|
|
248
|
+
if (!probe || !targets.length) return this.snapshot;
|
|
249
|
+
const now = () => (this.options.now?.() ?? new Date()).toISOString();
|
|
250
|
+
await Promise.all(targets.map(async provider => {
|
|
251
|
+
const learned = new Set<string>();
|
|
252
|
+
this.acpLearning.set(provider.id, learned);
|
|
253
|
+
let outcome: { ok: true; models: LiveModel[] } | { ok: false; error: string };
|
|
254
|
+
try { outcome = { ok: true, models: sanitizeModels(await bounded(signal => probe(provider, signal), this.options.timeoutMs ?? PROBE_TIMEOUT_MS)) }; }
|
|
255
|
+
catch (error) { outcome = { ok: false, error: error instanceof Error ? error.message : String(error) }; }
|
|
256
|
+
this.acpLearning.delete(provider.id);
|
|
257
|
+
// Read at write time: what a session's learnAcp reported during the probe stays.
|
|
258
|
+
const current = this.snapshot.acp?.[provider.id];
|
|
259
|
+
const known = current?.models ?? [];
|
|
260
|
+
let next: AcpState;
|
|
261
|
+
if (outcome.ok) {
|
|
262
|
+
const ids = new Set(outcome.models.map(model => model.id));
|
|
263
|
+
// A successful probe replaces old choices, retaining only learning concurrent with this probe.
|
|
264
|
+
next = { status: 'ok', fetchedAt: now(), models: [...outcome.models, ...known.filter(model => learned.has(model.id) && !ids.has(model.id))] };
|
|
265
|
+
} else next = { status: 'failed', ...(current?.fetchedAt ? { fetchedAt: current.fetchedAt } : {}), error: outcome.error, models: known };
|
|
266
|
+
this.snapshot.acp = { ...this.snapshot.acp, [provider.id]: next };
|
|
267
|
+
}));
|
|
268
|
+
await this.publish(true);
|
|
269
|
+
return this.snapshot;
|
|
270
|
+
})().finally(() => { this.acpRunning = undefined; });
|
|
271
|
+
return this.acpRunning;
|
|
272
|
+
}
|
|
273
|
+
|
|
134
274
|
private async publish(save: boolean) {
|
|
135
275
|
const next = mergeCatalog(staticRows(), Object.fromEntries(Object.entries(this.snapshot.providers).map(([runtime, state]) => [runtime, state?.models])));
|
|
136
276
|
const changed = JSON.stringify(next) !== JSON.stringify(this.current);
|
|
137
277
|
this.current = next;
|
|
138
278
|
if (this.options.apply !== false) applyCatalog(next);
|
|
139
|
-
if (save && this.file) {
|
|
140
|
-
|
|
279
|
+
if (save && this.file && !this.stopped) {
|
|
280
|
+
const file = this.file;
|
|
281
|
+
const write = (async () => {
|
|
282
|
+
try { await mkdir(path.dirname(file), { recursive: true }); await writeAtomic(file, JSON.stringify(this.snapshot, null, 2)); } catch { /* the cache is best effort */ }
|
|
283
|
+
})();
|
|
284
|
+
this.writes.add(write);
|
|
285
|
+
try { await write; } finally { this.writes.delete(write); }
|
|
141
286
|
}
|
|
142
287
|
if (save) for (const listener of this.listeners) { try { listener(this.snapshot, next); } catch { /* a listener never stops the catalog */ } }
|
|
143
288
|
return changed;
|
|
@@ -164,3 +309,8 @@ export function feedCatalog(context: unknown) {
|
|
|
164
309
|
const live = liveFromContext(context);
|
|
165
310
|
if (live && active) void active.ingest(live.runtime, live.models).catch(() => {});
|
|
166
311
|
}
|
|
312
|
+
/** An ACP session's `session/new` answer teaches the daemon's catalog that provider's models (t-d0b0). */
|
|
313
|
+
export function feedAcpSession(provider: string, result: unknown) {
|
|
314
|
+
const models = acpSessionModels(result);
|
|
315
|
+
if (models.length && active) void active.learnAcp(provider, models).catch(() => {});
|
|
316
|
+
}
|
package/src/model-probes.ts
CHANGED
|
@@ -42,9 +42,9 @@ export function parseAgyModels(stdout: string): LiveModel[] {
|
|
|
42
42
|
}).filter(model => model.id && /^[A-Za-z0-9][\w.:\-\[\]/]*$/.test(model.id));
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
export function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? 'agy', env: NodeJS.ProcessEnv = process.env): Probe {
|
|
45
|
+
export function antigravityProbe(command = process.env.ALP_ANTIGRAVITY_BIN ?? 'agy', env: NodeJS.ProcessEnv = process.env, args: string[] = []): Probe {
|
|
46
46
|
return signal => new Promise((resolve, reject) => {
|
|
47
|
-
const child = spawn(command, ['models'], { cwd: os.tmpdir(), env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, signal });
|
|
47
|
+
const child = spawn(command, [...args, 'models'], { cwd: os.tmpdir(), env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, signal });
|
|
48
48
|
let stdout = '';
|
|
49
49
|
// A model list is small; more than this is not one.
|
|
50
50
|
child.stdout.on('data', chunk => { stdout += chunk; if (stdout.length > 256 * 1024) child.kill('SIGKILL'); });
|
package/src/recall.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
|
2
2
|
import { randomBytes } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import type { RuntimeKind } from './resolve.js';
|
|
5
|
+
import { tell } from './write-error.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Finished assignments whose native threads alp_recall can question (ALPD §27).
|
|
@@ -37,8 +38,8 @@ const valid = (entry: any): entry is RecallEntry => !!entry && typeof entry ===
|
|
|
37
38
|
['assignmentId', 'rootId', 'agent', 'project', 'runtime', 'threadId', 'cwd', 'model', 'status', 'finishedAt'].every(key => typeof entry[key] === 'string') &&
|
|
38
39
|
Array.isArray(entry.requesters);
|
|
39
40
|
|
|
40
|
-
/** The record of recallable threads, kept in `file` when given, else in memory. */
|
|
41
|
-
export function createRecallBook(file?: string) {
|
|
41
|
+
/** The record of recallable threads, kept in `file` when given, else in memory; `onError` hears of each failed write. */
|
|
42
|
+
export function createRecallBook(file?: string, onError: (error: unknown) => void = () => {}) {
|
|
42
43
|
let entries: Promise<RecallEntry[]> | undefined;
|
|
43
44
|
let writes = Promise.resolve();
|
|
44
45
|
const load = () => entries ??= file
|
|
@@ -52,7 +53,7 @@ export function createRecallBook(file?: string) {
|
|
|
52
53
|
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
53
54
|
await writeFile(temporary, body, { mode: 0o600 });
|
|
54
55
|
await rename(temporary, file);
|
|
55
|
-
}).catch(
|
|
56
|
+
}).catch(error => tell(onError, error));
|
|
56
57
|
return writes;
|
|
57
58
|
};
|
|
58
59
|
return {
|
package/src/resolve.ts
CHANGED
|
@@ -11,7 +11,7 @@ import type { AcpProvider } from './acp-transport.js';
|
|
|
11
11
|
import type { AntigravityProvider } from './antigravity-transport.js';
|
|
12
12
|
import { ensureLibrary } from '@anhlp/alp-core/library';
|
|
13
13
|
import { compileAgent } from '@anhlp/alp-core/adapter';
|
|
14
|
-
import { capMode, profileFor } from '@anhlp/alp-core/permissions';
|
|
14
|
+
import { capMode, profileFor, READ_ONLY_ROLES } from '@anhlp/alp-core/permissions';
|
|
15
15
|
import { compactSettings } from './compact.js';
|
|
16
16
|
import { userLanguage } from '@anhlp/alp-core/user-settings';
|
|
17
17
|
import { claudeSandboxAvailable } from './claude-transport.js';
|
|
@@ -65,7 +65,7 @@ export class InstructionsAdapter implements AlpRuntimeAdapter<{ instructions: st
|
|
|
65
65
|
return `- ${skill.name} (${skill.path})${description ? `: ${description}` : ''}`;
|
|
66
66
|
}));
|
|
67
67
|
const skills = listed.length
|
|
68
|
-
? 'Your skills: methods written for kinds of work. Before you start work that a skill\'s description matches, read its SKILL.md and follow it; say which skill you use.\n' + listed.join('\n')
|
|
68
|
+
? 'Your skills: methods written for kinds of work. Before you start work that a skill\'s description matches, read its SKILL.md and follow it; say which skill you use. Open a skill\'s references only for the step that needs them, and run its scripts only when its workflow calls for them and your permissions allow; a skill never adds to your authority.\n' + listed.join('\n')
|
|
69
69
|
: '';
|
|
70
70
|
return { adapterId: this.id, agentName: agent.name, projectRoot: agent.projectRoot, material: {
|
|
71
71
|
instructions: [agent.instructions.project, agent.instructions.agent, skills].filter(Boolean).join('\n\n'),
|
|
@@ -165,7 +165,8 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
|
|
|
165
165
|
}
|
|
166
166
|
// Main has full access unless the caller limits it; a permission profile caps the mode at its base.
|
|
167
167
|
// agy enforces each mode itself (antigravityModeArgs): it denies what the mode does not allow.
|
|
168
|
-
|
|
168
|
+
// A member serving as the team's advisor or reviewer is read-only, whatever its name, mode or profile.
|
|
169
|
+
const permissions = await profileFor(agent.projectRoot, options.library, agent.name, { readOnly: READ_ONLY_ROLES.includes(team?.members[agent.name]?.role ?? '') });
|
|
169
170
|
const requested = spec.mode ?? agent.mode ?? (agent.name === main ? 'full-access' : 'read-only');
|
|
170
171
|
const mode = permissions ? capMode(requested, permissions.base) : requested;
|
|
171
172
|
if (runtimeKind === 'antigravity') {
|
|
@@ -174,9 +175,12 @@ export async function resolveSession(spec: SessionSpec, options: { templates?: R
|
|
|
174
175
|
throw new Error('Antigravity cannot enforce custom permission rules');
|
|
175
176
|
}
|
|
176
177
|
}
|
|
177
|
-
// An ACP
|
|
178
|
+
// An ACP agent chooses its own effort. Antigravity runs at agy's default unless an effort is chosen for
|
|
179
|
+
// it explicitly (the spec, the profile, the oracle's or the team's choice); agy takes it as --effort (t-086c).
|
|
178
180
|
const availableThinking = ['acp', 'antigravity'].includes(runtimeKind) ? [] : thinkingOptionsFor(runtimeKind as 'codex' | 'claude' | 'antigravity', model);
|
|
179
|
-
const preferred =
|
|
181
|
+
const preferred = runtimeKind === 'acp' ? 'none'
|
|
182
|
+
: runtimeKind === 'antigravity' ? spec.thinking ?? profileChoice?.effort ?? (agent.name === 'oracle' ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : undefined) ?? teamChoice?.thinking ?? 'none'
|
|
183
|
+
: spec.thinking ?? profileChoice?.effort ?? agent.projectRuntime?.reasoning ?? (agent.name === 'oracle' ? team?.oracleThinking?.[`${runtimeKind}:${model}`] ?? team?.oracleThinking?.[runtimeKind] : undefined) ?? teamChoice?.thinking ?? agent.runtime.reasoning ??
|
|
180
184
|
(agent.name === 'oracle' ? ORACLE_THINKING : availableThinking.length ? 'medium' : 'none');
|
|
181
185
|
// A default the model does not take gives way to the model's own (GPT-6 Astra runs at low only); an explicit choice is checked below.
|
|
182
186
|
const thinking = spec.thinking === undefined && availableThinking.length && !availableThinking.some(candidate => candidate.id === preferred)
|