@trama-dev/runtime 0.1.5 → 0.2.0

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.
@@ -1,5 +1,6 @@
1
- import { createAgentSession, SessionManager, DefaultResourceLoader, } from "@mariozechner/pi-coding-agent";
2
- import { getModel } from "@mariozechner/pi-ai";
1
+ import { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir, } from "@earendil-works/pi-coding-agent";
2
+ /** The pi version this runtime is built against (recorded in each project's meta.json). */
3
+ export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
3
4
  /** Strip markdown code fences and trim whitespace. */
4
5
  export function stripCodeFences(text) {
5
6
  const trimmed = text.trim();
@@ -10,6 +11,8 @@ export function stripCodeFences(text) {
10
11
  }
11
12
  return trimmed;
12
13
  }
14
+ /** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
15
+ const warnedUnknownModels = new Set();
13
16
  export class PiAdapter {
14
17
  config;
15
18
  cwd;
@@ -24,11 +27,13 @@ export class PiAdapter {
24
27
  async createSession(systemPrompt, signal) {
25
28
  if (signal?.aborted)
26
29
  throw new Error("Aborted");
30
+ const agentDir = getAgentDir();
27
31
  const resourceLoader = new DefaultResourceLoader({
28
32
  cwd: this.cwd,
33
+ agentDir,
29
34
  noExtensions: true,
30
35
  noSkills: true,
31
- ...(systemPrompt && { appendSystemPrompt: systemPrompt }),
36
+ ...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
32
37
  });
33
38
  // Race an async step against the abort signal.
34
39
  // Returns the result on success, or rejects with "Aborted" on abort.
@@ -53,15 +58,32 @@ export class PiAdapter {
53
58
  await raceAbort(resourceLoader.reload());
54
59
  if (signal?.aborted)
55
60
  throw new Error("Aborted");
61
+ // Resolve the model through pi's model runtime (built-in catalog plus the
62
+ // user's models.json). An unknown provider/model resolves to undefined, in
63
+ // which case pi falls back to its own default selection.
64
+ const modelRuntime = await raceAbort(ModelRuntime.create({ signal }));
65
+ if (signal?.aborted)
66
+ throw new Error("Aborted");
67
+ const model = modelRuntime.getModel(this.config.provider, this.config.model);
56
68
  // Keep a reference to the raw promise so we can clean up a late-arriving session
57
69
  const sessionPromise = createAgentSession({
58
70
  cwd: this.cwd,
59
- model: getModel(this.config.provider, this.config.model),
60
- sessionManager: SessionManager.inMemory(),
71
+ agentDir,
72
+ modelRuntime,
73
+ model,
74
+ sessionManager: SessionManager.inMemory(this.cwd),
61
75
  resourceLoader,
62
76
  });
63
77
  try {
64
78
  const { session } = await raceAbort(sessionPromise);
79
+ if (!model) {
80
+ // With nothing to fall back to, pi reports a placeholder model that is
81
+ // not in its catalog — only name the fallback when it is a real one.
82
+ const picked = session.model;
83
+ const fallback = picked && modelRuntime.getModel(picked.provider, picked.id)
84
+ ? `${picked.provider}/${picked.id}` : null;
85
+ this.warnUnknownModel(fallback);
86
+ }
65
87
  return session;
66
88
  }
67
89
  catch (err) {
@@ -70,6 +92,21 @@ export class PiAdapter {
70
92
  throw err;
71
93
  }
72
94
  }
95
+ /**
96
+ * The configured provider/model is not in pi's catalog, so pi picked a model
97
+ * on its own. Say so once — otherwise a typo silently runs a different model.
98
+ */
99
+ warnUnknownModel(fallback) {
100
+ const requested = `${this.config.provider}/${this.config.model}`;
101
+ if (warnedUnknownModels.has(requested))
102
+ return;
103
+ warnedUnknownModels.add(requested);
104
+ console.warn(`[trama] warning: model "${requested}" was not found in pi's model catalog. ` +
105
+ (fallback
106
+ ? `pi is falling back to "${fallback}". `
107
+ : `pi has no fallback model available, so LLM calls will fail. `) +
108
+ `Check "provider" and "model" in ~/.trama/config.json or the project's meta.json.`);
109
+ }
73
110
  extractText(session) {
74
111
  const messages = session.state.messages;
75
112
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -86,7 +123,9 @@ export class PiAdapter {
86
123
  /**
87
124
  * Abort cancellation relies on session.dispose() interrupting session.prompt().
88
125
  * This is an upstream contract of pi-coding-agent — if dispose() does not
89
- * actually reject the in-flight prompt, the abort signal will not terminate the call.
126
+ * actually settle the in-flight prompt, the abort signal will not terminate the call.
127
+ * pi 1.x settles the prompt by resolving it (not rejecting), so abort is
128
+ * re-checked after prompt() returns.
90
129
  */
91
130
  async ask(prompt, options) {
92
131
  const signal = options?.signal;
@@ -102,6 +141,10 @@ export class PiAdapter {
102
141
  if (signal?.aborted)
103
142
  throw new Error("Aborted");
104
143
  await session.prompt(prompt);
144
+ // An aborted prompt resolves with no usable answer — report it as an abort,
145
+ // not as an empty LLM response.
146
+ if (signal?.aborted)
147
+ throw new Error("Aborted");
105
148
  const text = this.extractText(session);
106
149
  if (!text)
107
150
  throw new Error("Empty response from LLM");
@@ -0,0 +1,29 @@
1
+ export interface ProgramResult {
2
+ status: "done" | "yielded" | "failed";
3
+ /** Yield reason, or error summary for failed. */
4
+ reason?: string;
5
+ /** From ctx.done(result), if provided. */
6
+ result?: unknown;
7
+ }
8
+ export interface PiAdapterConfig {
9
+ provider: string;
10
+ model: string;
11
+ }
12
+ export interface RunOptions {
13
+ projectDir: string;
14
+ maxRepairAttempts?: number;
15
+ timeout?: number;
16
+ args?: Record<string, unknown>;
17
+ /** Shared workspace directory. When set, workspace.* API is enabled for the program. */
18
+ workspaceDir?: string;
19
+ }
20
+ export interface RepairInput {
21
+ programSource: string;
22
+ error: string;
23
+ runtimeTypes: string;
24
+ }
25
+ export interface TramaConfig extends PiAdapterConfig {
26
+ maxRepairAttempts: number;
27
+ defaultTimeout: number;
28
+ defaultMaxIterations: number;
29
+ }
@@ -0,0 +1,3 @@
1
+ // Runner-side types: what callers of "@trama-dev/runtime/runner" and the runtime's
2
+ // own modules use. Nothing here is visible to a program.ts.
3
+ export {};
package/dist/runner.d.ts CHANGED
@@ -1,57 +1,62 @@
1
- import type { RunOptions, TramaConfig, ProgramResult } from "./types.js";
1
+ import type { RunOptions, TramaConfig, ProgramResult } from "./runner-types.js";
2
2
  import { PiAdapter } from "./pi-adapter.js";
3
- export declare const PI_VERSION: string;
4
3
  /**
5
- * Ensure project has ESM package.json and .gitignore.
6
- * If package.json exists but lacks "type": "module", patches it in.
4
+ * Everything a project directory needs around program.ts before it can run:
5
+ * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
6
+ * @trama-dev packages it can import.
7
+ * Idempotent — called before every run, so a freshly cloned project just works.
7
8
  */
8
9
  export declare function ensureProjectScaffold(projectDir: string): void;
9
10
  /**
10
- * Simplified API reference for LLM system prompts.
11
- * NOT the canonical type definitions (those live in types.ts).
12
- * Kept as a readable string rather than auto-generated, because the LLM
13
- * needs a concise reference, not the full implementation types.
14
- * If types.ts changes, review whether this summary needs updating.
11
+ * The program-facing API, as shown to the LLM when it writes or repairs a
12
+ * program. This is the declaration file generated from types.ts, so the prompt
13
+ * cannot drift from the real API — doc comments included.
15
14
  */
16
- export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n readonly resumed: boolean;\n readonly yieldReason: string | null;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n ready(data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n yield(reason: string): Promise<never>;\n}\n\nexport interface Agent {\n instruct(prompt: string, options?: { system?: string }): Promise<string>;\n /** @deprecated Use instruct() instead */\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport type ObserveResult = string | Array<{ path: string; content: string }>;\n\nexport interface Workspace {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n list(pattern: string): Promise<string[]>;\n observe(pattern: string, options?: { expect?: number; timeout?: number }): Promise<ObserveResult>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;\nexport declare const workspace: Workspace;";
15
+ export declare const RUNTIME_TYPES: string;
17
16
  export declare function loadConfig(): TramaConfig;
17
+ /** The global config, with the model/provider a project was created with taking precedence. */
18
+ export declare function loadProjectConfig(projectDir: string): TramaConfig;
18
19
  export declare function loadState(projectDir: string): Record<string, unknown>;
19
20
  /**
20
- * Copy current program.ts to history/NNNN.ts and append to index.jsonl.
21
+ * Save the current program.ts as the next version: copy it to history/NNNN.ts
22
+ * and record why in index.jsonl.
21
23
  *
22
- * WARNING: Do NOT use this for create-time repair attempts.
23
- * Create-time repairs go to index.jsonl only (reason: "create-repair").
24
+ * Repairs made while validating a create or update are NOT versions of their
25
+ * own — they are noted in index.jsonl only (reason "create-repair" /
26
+ * "update-repair"), and the validated program becomes the create/update version.
24
27
  */
25
28
  export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
26
- /** Record all files in a directory with their size and mtime for change detection. */
27
- export declare function snapshotDir(dir: string, prefix?: string): Map<string, {
29
+ type DirSnapshot = Map<string, {
28
30
  size: number;
29
31
  mtimeMs: number;
30
32
  }>;
33
+ /** Record all files in a directory with their size and mtime for change detection. */
34
+ export declare function snapshotDir(dir: string, prefix?: string): DirSnapshot;
31
35
  /**
32
36
  * Commit workspace changes from a temp workspace back to the real workspace,
33
37
  * using a three-way check to avoid overwriting concurrent updates by other participants.
34
38
  *
35
- * @param tempDir - temp workspace after the rerun (source of changes)
39
+ * @param tempDir - temp workspace after the run (source of changes)
36
40
  * @param realDir - real shared workspace (destination)
37
- * @param tempBefore - temp workspace snapshot before the rerun (detects what the rerun changed)
41
+ * @param tempBefore - temp workspace snapshot before the run (detects what the run changed)
38
42
  * @param realSeed - real workspace snapshot at seed time (detects concurrent changes)
39
43
  *
40
- * For each file changed in the temp workspace during the rerun:
41
- * - New file (not in tempBefore): always copy to real workspace.
42
- * - Modified file: only copy if the real workspace's current state still matches
43
- * realSeed. If it doesn't, another participant changed it concurrently — skip.
44
+ * For each file the run created or modified in the temp workspace:
45
+ * - New file: copied unless that path has meanwhile appeared in the real workspace.
46
+ * - Modified file: copied only if the real workspace's copy still matches realSeed.
47
+ * If it doesn't, another participant changed or removed it concurrently — skip.
48
+ * Best-effort: anything that cannot be committed safely is skipped, never thrown.
44
49
  */
45
- export declare function commitWorkspaceChanges(tempDir: string, realDir: string, tempBefore: Map<string, {
46
- size: number;
47
- mtimeMs: number;
48
- }>, realSeed: Map<string, {
49
- size: number;
50
- mtimeMs: number;
51
- }>): void;
50
+ export declare function commitWorkspaceChanges(tempDir: string, realDir: string, tempBefore: DirSnapshot, realSeed: DirSnapshot): void;
52
51
  /**
53
- * Snapshot a directory, run fn, restore from snapshot if fn returns false
54
- * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
52
+ * Run fn against a directory that can be put back exactly as it was: if fn
53
+ * returns keep:false or throws, the directory is rolled back. Returns fn's value.
54
+ *
55
+ * The snapshot is a hidden copy next to the directory, on the same file
56
+ * system, so rolling back is two renames — move the directory aside, move the
57
+ * snapshot into its place — and at no point does the content exist nowhere.
58
+ * (If the process is killed outright, the snapshot is left behind beside the
59
+ * directory: it is the pre-change state.)
55
60
  */
56
61
  export declare function withSnapshot<T>(dir: string, fn: () => Promise<{
57
62
  keep: boolean;
@@ -59,10 +64,16 @@ export declare function withSnapshot<T>(dir: string, fn: () => Promise<{
59
64
  }>): Promise<T>;
60
65
  /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
61
66
  export declare function withTempDir<T>(prefix: string, fn: (dir: string) => Promise<T>): Promise<T>;
62
- export declare function resolveSmokeTimeout(timeout?: number): number;
63
- export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter, reason: "create" | "update", options?: {
64
- timeout?: number;
65
- maxRepairAttempts?: number;
66
- maxIterations?: number;
67
+ /**
68
+ * Validate a freshly generated program.ts by running it (with repair) in a
69
+ * throwaway copy of the project, so the validation run's file side effects
70
+ * don't persist. On success the validated — possibly repaired — program is
71
+ * copied back. Throws if it cannot be made to run.
72
+ */
73
+ export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter, reason: "create" | "update", options: {
74
+ timeout: number;
75
+ maxRepairAttempts: number;
76
+ maxIterations: number;
67
77
  }): Promise<void>;
68
78
  export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
79
+ export {};