@howaboua/pi-durable-code 0.0.0-stage → 0.10.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.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +251 -0
  3. package/README.md +93 -2
  4. package/dist/activation.js +4759 -0
  5. package/dist/code/src/activation.d.ts +5 -0
  6. package/dist/code/src/binary.d.ts +6 -0
  7. package/dist/code/src/cell-output.d.ts +33 -0
  8. package/dist/code/src/engine.d.ts +16 -0
  9. package/dist/code/src/history.d.ts +6 -0
  10. package/dist/code/src/host-assets.d.ts +4 -0
  11. package/dist/code/src/host-connection.d.ts +29 -0
  12. package/dist/code/src/host-process.d.ts +21 -0
  13. package/dist/code/src/host-protocol.d.ts +54 -0
  14. package/dist/code/src/host-runtime.d.ts +21 -0
  15. package/dist/code/src/host-session.d.ts +24 -0
  16. package/dist/code/src/index.d.ts +32 -0
  17. package/dist/code/src/install-host.d.ts +7 -0
  18. package/dist/code/src/presentation.d.ts +22 -0
  19. package/dist/code/src/result.d.ts +4 -0
  20. package/dist/code/src/runtime-contract.d.ts +24 -0
  21. package/dist/code/src/runtime-response.d.ts +2 -0
  22. package/dist/code/src/runtime-tools.d.ts +7 -0
  23. package/dist/execution/src/cell-contract.d.ts +49 -0
  24. package/dist/execution/src/cell-observation.d.ts +7 -0
  25. package/dist/execution/src/cell-progress.d.ts +4 -0
  26. package/dist/execution/src/cell-task.d.ts +17 -0
  27. package/dist/execution/src/cell-tools.d.ts +8 -0
  28. package/dist/execution/src/cells.d.ts +14 -0
  29. package/dist/execution/src/command-backend.d.ts +22 -0
  30. package/dist/execution/src/controls.d.ts +3 -0
  31. package/dist/execution/src/custom-command-config.d.ts +21 -0
  32. package/dist/execution/src/custom-commands.d.ts +62 -0
  33. package/dist/execution/src/exec-source.d.ts +21 -0
  34. package/dist/execution/src/forwarded-tools.d.ts +21 -0
  35. package/dist/execution/src/forwarding-hook.d.ts +6 -0
  36. package/dist/execution/src/forwarding.d.ts +15 -0
  37. package/dist/execution/src/history.d.ts +14 -0
  38. package/dist/execution/src/index.d.ts +6 -0
  39. package/dist/execution/src/invocation-state.d.ts +26 -0
  40. package/dist/execution/src/invocation.d.ts +35 -0
  41. package/dist/execution/src/native-tools.d.ts +11 -0
  42. package/dist/execution/src/nested-call.d.ts +26 -0
  43. package/dist/execution/src/nested-result.d.ts +8 -0
  44. package/dist/execution/src/nested.d.ts +3 -0
  45. package/dist/execution/src/output.d.ts +48 -0
  46. package/dist/execution/src/presentation.d.ts +59 -0
  47. package/dist/execution/src/progress.d.ts +23 -0
  48. package/dist/execution/src/projection.d.ts +5 -0
  49. package/dist/execution/src/shell/backend.d.ts +28 -0
  50. package/dist/execution/src/shell/format.d.ts +2 -0
  51. package/dist/execution/src/shell/node-backend.d.ts +9 -0
  52. package/dist/execution/src/shell/output.d.ts +19 -0
  53. package/dist/execution/src/shell/process-session.d.ts +50 -0
  54. package/dist/execution/src/shell/results.d.ts +14 -0
  55. package/dist/execution/src/shell/session-manager.d.ts +46 -0
  56. package/dist/execution/src/shell/session-store.d.ts +53 -0
  57. package/dist/execution/src/shell/shell-args.d.ts +4 -0
  58. package/dist/execution/src/shell/shell.d.ts +14 -0
  59. package/dist/execution/src/shell/wait.d.ts +7 -0
  60. package/dist/execution/src/shell.d.ts +14 -0
  61. package/dist/execution/src/tool-contract.d.ts +34 -0
  62. package/dist/execution/src/tool-origin.d.ts +11 -0
  63. package/dist/execution/src/tool-source.d.ts +6 -0
  64. package/dist/execution/src/tool-value.d.ts +3 -0
  65. package/dist/execution/src/wait-session.d.ts +6 -0
  66. package/dist/history.js +315 -0
  67. package/dist/index.js +5063 -0
  68. package/dist/presentation.js +198 -0
  69. package/package.json +77 -5
@@ -0,0 +1,15 @@
1
+ import { type ConversationId, type TaskId, type ToolExecutionResult, type Tx } from "@earendil-works/pi-durable";
2
+ import type { ForwardedToolCall, ForwardedToolCalls, ForwardedToolStatus } from "./forwarded-tools.ts";
3
+ import type { ExecutionResultReceipt } from "./presentation.ts";
4
+ /** The budget applies only to display copies, never invocation inputs or runtime results. */
5
+ export declare function boundForwardedToolCalls(value: ForwardedToolCalls, budget: number): ForwardedToolCalls;
6
+ export declare function displayResult(result: ToolExecutionResult, budget: number): ExecutionResultReceipt;
7
+ export declare function forwardedStatus(result: ToolExecutionResult, fallback: ForwardedToolStatus): ForwardedToolStatus;
8
+ /** Update the current cell's existing receipt; no transcript entry or parallel history. */
9
+ export declare function forwardCall(tx: Tx, cellId: TaskId | undefined, call: ForwardedToolCall, admission?: boolean, nativeTask?: {
10
+ taskId: TaskId;
11
+ ownerTaskId: TaskId;
12
+ }): Promise<void>;
13
+ export declare function forwardInvocationResult(tx: Tx, taskId: TaskId, result: ToolExecutionResult, status: ForwardedToolStatus): Promise<void>;
14
+ /** Acquire native progress/results while the caller's task-scoped receipts still exist. */
15
+ export declare function captureNativeCalls(tx: Tx, conversationId: ConversationId, owner: TaskId, cellId: TaskId | undefined): Promise<void>;
@@ -0,0 +1,14 @@
1
+ import type { Context } from "@earendil-works/chord";
2
+ import type { ConversationId, Harness } from "@earendil-works/pi-durable";
3
+ import type { ForwardedToolCalls } from "./forwarded-tools.ts";
4
+ export interface ExecutionHistoryRequest {
5
+ readonly conversationId: ConversationId;
6
+ readonly cellIds: readonly string[];
7
+ readonly maxOutputTokens?: number;
8
+ }
9
+ type HistoryHarness = Pick<Harness, "conversation" | "getTask" | "commit">;
10
+ /** Verified retained direct calls only, not a reconstructed native descendant graph.
11
+ * Current fork-visible history excludes later results from the parent conversation.
12
+ */
13
+ export declare function executionHistory(mode: "notebook" | "code" | "worker-code"): (harness: HistoryHarness, request: ExecutionHistoryRequest, context: Context) => Promise<ReadonlyMap<string, ForwardedToolCalls>>;
14
+ export {};
@@ -0,0 +1,6 @@
1
+ export type { CellObservation } from "./cell-contract.ts";
2
+ export { type CellCoordinatorOptions, createCellCoordinator } from "./cells.ts";
3
+ export { adaptiveWaitMs, MAX_CODE_MODE_OUTPUT_TOKENS } from "./exec-source.ts";
4
+ export { readToolContract } from "./tool-contract.ts";
5
+ export { directToolYieldTime } from "./tool-source.ts";
6
+ export { toolValue } from "./tool-value.ts";
@@ -0,0 +1,26 @@
1
+ import { type JsonRepresentation, type JsonValue } from "@earendil-works/chord";
2
+ import { type TaskId, type ToolExecutionResult } from "@earendil-works/pi-durable";
3
+ import type { ForwardedToolCalls } from "./forwarded-tools.ts";
4
+ type StoredResult = JsonRepresentation<ToolExecutionResult>;
5
+ export type InvocationState = {
6
+ result: StoredResult;
7
+ checkpoint?: JsonValue;
8
+ yieldCount?: number;
9
+ isolated?: boolean;
10
+ droppedBytes?: number;
11
+ droppedLines?: number;
12
+ forwardingCellId?: TaskId;
13
+ forwardingBudget?: number;
14
+ forwardedToolCalls?: JsonRepresentation<ForwardedToolCalls>;
15
+ /** Admission identities only, bounded to retained display calls; native slots may retire first. */
16
+ forwardedNativeTasks?: {
17
+ callId: string;
18
+ taskId: TaskId;
19
+ ownerTaskId: TaskId;
20
+ }[];
21
+ };
22
+ export declare const InvocationDoc: import("@earendil-works/pi-durable").TaskDocToken<InvocationState>;
23
+ /** Version-one task receipts remain readable after their task documents retire. */
24
+ export declare function readStoredResult(result: ToolExecutionResult): ToolExecutionResult;
25
+ export declare function storeResult(result: ToolExecutionResult): StoredResult;
26
+ export {};
@@ -0,0 +1,35 @@
1
+ import { type Context } from "@earendil-works/chord";
2
+ import type { TextContent } from "@earendil-works/pi-ai";
3
+ import { type TaskRuntime, type ToolDiagnostic, type ToolExecutionApi, type ToolExecutionResult, type ToolRegistration } from "@earendil-works/pi-durable";
4
+ import { OutputBuffer, type OutputLimits } from "./output.ts";
5
+ import { Progress } from "./progress.ts";
6
+ export declare function executionError(code: string, message: string): ToolExecutionResult;
7
+ export declare function errorText(error: unknown): string;
8
+ /** One invocation owns its output, progress commits, environment and child-task API. */
9
+ export declare function createInvocation<I, S, R, H extends object>(runtime: TaskRuntime<I, S, R, H>, tool: Pick<ToolRegistration, "outputLimits" | "replay">, context: Context): {
10
+ /** Resolve the environment after the tracker exists, so environment failures still settle bounded hook results. */
11
+ executionApi(): Promise<ToolExecutionApi>;
12
+ finish(result: ToolExecutionResult): Promise<{
13
+ result: ToolExecutionResult;
14
+ pending: {
15
+ promise: Promise<void>;
16
+ resolve(): void;
17
+ reject(error: unknown): void;
18
+ }[];
19
+ retained: {
20
+ readonly text: string;
21
+ readonly droppedBytes: number;
22
+ readonly droppedLines: number;
23
+ };
24
+ content: (import("@earendil-works/pi-ai").ImageContent | TextContent)[];
25
+ }>;
26
+ stop(error: unknown): Promise<void>;
27
+ limits: OutputLimits;
28
+ output: OutputBuffer;
29
+ progress: Progress;
30
+ };
31
+ export declare function boundResult(result: ToolExecutionResult, limits: OutputLimits): ToolExecutionResult;
32
+ export declare function truncation(dropped: {
33
+ droppedLines: number;
34
+ droppedBytes: number;
35
+ }, retain?: "head" | "tail"): ToolDiagnostic;
@@ -0,0 +1,11 @@
1
+ import { type Context } from "@earendil-works/chord";
2
+ import { type JsonObject, type NestedToolExecutionResult, type TaskRuntime } from "@earendil-works/pi-durable";
3
+ export declare function nativeToolCalls<I, S, R, H extends object>(runtime: TaskRuntime<I, S, R, H>, callId: string, replay: "safe" | "unsafe" | undefined, assertLive: () => void, context: Context): {
4
+ execute: (name: string, args: JsonObject, context: Context, options?: {
5
+ readonly key?: string;
6
+ readonly progress?: boolean;
7
+ }) => Promise<NestedToolExecutionResult>;
8
+ finish(): Promise<void>;
9
+ };
10
+ /** Custom cell callers own native nested slots too, including after recovery. */
11
+ export declare function cleanupNativeCalls<I, S, R, H extends object>(runtime: TaskRuntime<I, S, R, H>, context: Context): Promise<void>;
@@ -0,0 +1,26 @@
1
+ import type { JsonValue } from "@earendil-works/chord";
2
+ import type { ToolCall } from "@earendil-works/pi-ai";
3
+ import { type Agent, type HookApi, type JsonObject, type TaskId, type TaskRuntime, type ToolExecutionResult, type ToolHookCall, type ToolHooks, type ToolRegistration } from "@earendil-works/pi-durable";
4
+ export type NestedInput = {
5
+ name: string;
6
+ arguments: JsonValue;
7
+ cellId?: TaskId;
8
+ parent?: NonNullable<ToolHookCall["parent"]>;
9
+ };
10
+ export type Checkpoint = {
11
+ phase: "call";
12
+ } | {
13
+ phase: "execute";
14
+ arguments: JsonObject;
15
+ replay: "safe" | "unsafe";
16
+ };
17
+ export type Runtime = TaskRuntime<NestedInput, Checkpoint, ToolExecutionResult, Record<string, never>>;
18
+ export declare function nestedCall(runtime: Runtime, input: NestedInput): ToolHookCall;
19
+ export declare function checked(tool: ToolRegistration, call: ToolCall, args: unknown): JsonObject;
20
+ /** Decode equivalent structured requests before registration preparation and hooks. */
21
+ export declare function prepareNestedInput(tool: ToolRegistration, input: unknown): unknown;
22
+ /** Public hook registrations erase their handler type. Select by the built-in task name before restoring it. */
23
+ export declare function eachHook<K extends keyof ToolHooks>(agent: Agent, name: K, api: HookApi & {
24
+ signal: AbortSignal;
25
+ report(error: unknown): void;
26
+ }, invoke: (hook: ToolHooks[K]) => Promise<void>): Promise<void>;
@@ -0,0 +1,8 @@
1
+ import { type Context } from "@earendil-works/chord";
2
+ import type { ToolCall } from "@earendil-works/pi-ai";
3
+ import { type JsonObject, type ToolExecutionResult } from "@earendil-works/pi-durable";
4
+ import type { Runtime } from "./nested-call.ts";
5
+ /** An audit record, deliberately with no assistant or tool-result model contribution. */
6
+ export declare const NestedResultEntry: import("@earendil-works/pi-durable").Entry<JsonObject>;
7
+ export declare function interrupted(runtime: Runtime, call: ToolCall, code: "interrupted" | "aborted", message: string, context: Context): Promise<void>;
8
+ export declare function settle(runtime: Runtime, call: ToolCall, result: ToolExecutionResult, ending: "completed" | "failed" | "aborted", context: Context): Promise<void>;
@@ -0,0 +1,3 @@
1
+ import { type ToolExecutionResult } from "@earendil-works/pi-durable";
2
+ import { type Checkpoint, type NestedInput } from "./nested-call.ts";
3
+ export declare function createNestedToolTask(name: string): import("@earendil-works/pi-durable").Task<NestedInput, Checkpoint, ToolExecutionResult, Record<string, never>>;
@@ -0,0 +1,48 @@
1
+ import type { ShellOutputSkip } from "@earendil-works/pi-durable/env";
2
+ /** Retention limits of one tool's output. */
3
+ export type OutputLimits = {
4
+ readonly maxBytes: number;
5
+ readonly maxLines: number;
6
+ readonly retain: "head" | "tail";
7
+ };
8
+ /** Retained output and what the limits dropped. */
9
+ type BoundedOutput = {
10
+ readonly text: string;
11
+ readonly droppedBytes: number;
12
+ readonly droppedLines: number;
13
+ };
14
+ /** An exact slice of the input within the limits, and what it left out. */
15
+ type OutputSlice = {
16
+ readonly text: string;
17
+ readonly bytes: number;
18
+ readonly droppedBytes: number;
19
+ readonly droppedLines: number;
20
+ };
21
+ /**
22
+ * Bound `text` to whole lines within the limits: the first lines for `head`, the last lines for `tail`. The result is an
23
+ * exact slice, trailing newline included. A single line longer than `maxBytes` is cut at the byte limit on a character
24
+ * boundary.
25
+ */
26
+ export declare function boundOutput(text: string, limits: OutputLimits): OutputSlice;
27
+ /**
28
+ * Bounded running output of one tool call. Accepting a chunk costs time proportional to the chunk: head retention stops
29
+ * storing once the window is full, and tail retention drops stored text the window no longer needs when it snapshots.
30
+ * Counts of the whole stream are kept so the dropped totals stay exact.
31
+ */
32
+ export declare class OutputBuffer {
33
+ #private;
34
+ constructor(limits: OutputLimits);
35
+ /** Bytes currently held; bounded by the limits plus one chunk. */
36
+ get storedBytes(): number;
37
+ /**
38
+ * Accept a chunk; returns whether anything was accepted. `skipped` is output omitted right before the chunk, which
39
+ * must be more than the tail window by at least one byte or line (`ShellOutputInfo.skipped`); only tail retention
40
+ * accepts it.
41
+ */
42
+ push(chunk: string | Uint8Array, skipped?: ShellOutputSkip): boolean;
43
+ /** Flush an incomplete trailing character as a replacement character; call when the stream ends. */
44
+ end(): void;
45
+ /** Retained, sanitized output and what the limits dropped from the whole stream. */
46
+ snapshot(): BoundedOutput;
47
+ }
48
+ export {};
@@ -0,0 +1,59 @@
1
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
2
+ readonly [key: string]: JsonValue;
3
+ };
4
+ export type ExecutionCellStatus = "running" | "completed" | "failed" | "aborted" | "interrupted";
5
+ export interface ExecutionCellReference {
6
+ readonly id: string;
7
+ readonly status: ExecutionCellStatus;
8
+ }
9
+ /** Display receipt only. Usage and tool controls remain owned by Durable. */
10
+ export interface ExecutionResultReceipt {
11
+ readonly content: readonly ({
12
+ readonly type: "text";
13
+ readonly text: string;
14
+ } | {
15
+ readonly type: "image";
16
+ readonly data: string;
17
+ readonly mimeType: string;
18
+ })[];
19
+ readonly isError: boolean;
20
+ readonly details: JsonValue;
21
+ readonly diagnostics: readonly {
22
+ readonly severity: "info" | "warn" | "error";
23
+ readonly message: string;
24
+ readonly code?: string;
25
+ }[];
26
+ }
27
+ /** Host-projected identity and independently acquired, bounded exec/wait or control receipt. */
28
+ export interface ExecutionPresentationState {
29
+ readonly cell: ExecutionCellReference | null;
30
+ readonly result: ExecutionResultReceipt | null;
31
+ }
32
+ export interface ExecutionSummaryModel {
33
+ readonly title: string;
34
+ readonly cell: ExecutionCellReference | null;
35
+ readonly hasResult: boolean;
36
+ readonly isError: boolean | null;
37
+ }
38
+ export declare function parseExecutionResultReceipt(value: JsonValue | undefined): ExecutionResultReceipt | null;
39
+ /** No acquisition, invocation, cancellation, replay or runtime-status inference. */
40
+ declare function parseExecutionPresentationState(value: JsonValue): ExecutionPresentationState;
41
+ export declare function executionCapability(id: string, actions: readonly string[]): {
42
+ id: string;
43
+ version: number;
44
+ actions: readonly string[];
45
+ streams: readonly ["results"];
46
+ presentations: readonly ["summary", "detail"];
47
+ parseState: typeof parseExecutionPresentationState;
48
+ };
49
+ export declare function executionSummary(title: string): {
50
+ id: string;
51
+ select: (state: ExecutionPresentationState) => ExecutionSummaryModel;
52
+ requests: readonly ["detail"];
53
+ };
54
+ export declare const executionDetail: {
55
+ id: string;
56
+ select: (state: ExecutionPresentationState) => ExecutionPresentationState;
57
+ requests: readonly [];
58
+ };
59
+ export {};
@@ -0,0 +1,23 @@
1
+ /** Each progress commit buys a pause proportional to what it wrote. */
2
+ export declare const PROGRESS_BYTES_PER_SECOND: number;
3
+ type ProgressWaiter = {
4
+ promise: Promise<void>;
5
+ resolve(): void;
6
+ reject(error: unknown): void;
7
+ };
8
+ /**
9
+ * Adaptive progress commits, like the environment's shell output capture: the first change after an idle period
10
+ * commits at once; each commit then delays the next by the configured interval and its written size at 100 KiB/s. At most
11
+ * one commit is in flight; changes made meanwhile coalesce into the next one.
12
+ */
13
+ export declare class Progress {
14
+ #private;
15
+ constructor(write: () => Promise<number>, onError: (error: unknown) => void, minIntervalMs: number);
16
+ /** Schedule a commit. */
17
+ mark(): void;
18
+ /** Schedule a commit; the promise settles with the commit that includes this change. */
19
+ markAndWait(): Promise<void>;
20
+ /** Stop committing and wait for the commit in flight; returns the waiters the final commit must settle. */
21
+ stop(): Promise<ProgressWaiter[]>;
22
+ }
23
+ export {};
@@ -0,0 +1,5 @@
1
+ import { type Harness } from "@earendil-works/pi-durable";
2
+ export declare function providerProjection(surfaceTools: readonly string[]): {
3
+ bind(harness: Pick<Harness, "conversation">): void;
4
+ hook: import("@earendil-works/pi-durable").HookRegistration;
5
+ };
@@ -0,0 +1,28 @@
1
+ export type ShellOutputStream = "stdout" | "stderr" | "pty";
2
+ export interface ShellSpawnRequest {
3
+ readonly shell: string;
4
+ readonly args: readonly string[];
5
+ readonly cwd: string;
6
+ readonly env: NodeJS.ProcessEnv;
7
+ readonly tty: boolean;
8
+ }
9
+ export interface ShellProcessEvents {
10
+ /** Bytes may split UTF-8 characters. A backend can also deliver already-decoded text. */
11
+ output(stream: ShellOutputStream, chunk: Uint8Array | string): void;
12
+ /** Deliver once, after streams close or the backend's documented drain grace expires. */
13
+ closed(exitCode: number): void;
14
+ }
15
+ export interface ShellProcess {
16
+ write(chars: string): Promise<void>;
17
+ /** Idempotent. Must stop the owned process and release streams before resolving. */
18
+ terminate(): Promise<void>;
19
+ }
20
+ /** Explicit native process capability. Implement this for a sandbox or remote namespace. */
21
+ export interface ShellProcessBackend {
22
+ readonly environmentId: string;
23
+ readonly platform: string;
24
+ readonly env: NodeJS.ProcessEnv;
25
+ readonly defaultShell: string;
26
+ /** Startup failure rejects. Never substitute a different host or process backend. */
27
+ spawn(request: ShellSpawnRequest, events: ShellProcessEvents): Promise<ShellProcess>;
28
+ }
@@ -0,0 +1,2 @@
1
+ import type { UnifiedExecResult } from "./session-store.ts";
2
+ export declare function formatUnifiedExecResult(result: UnifiedExecResult): string;
@@ -0,0 +1,9 @@
1
+ import type { ShellProcessBackend } from "./backend.ts";
2
+ export interface NodeShellBackendOptions {
3
+ /** Bind only to a namespace the host has verified is local. */
4
+ environmentId: string;
5
+ env?: NodeJS.ProcessEnv;
6
+ defaultShell?: string;
7
+ }
8
+ /** Local child_process and node-pty capability. Construction does not start a process. */
9
+ export declare function createNodeShellBackend(options: NodeShellBackendOptions): ShellProcessBackend;
@@ -0,0 +1,19 @@
1
+ export interface ExecOutputSessionState {
2
+ buffer: string;
3
+ bufferStartOffset: number;
4
+ emittedOffset: number;
5
+ }
6
+ export declare function normalizePipeOutput(text: string): string;
7
+ export declare function truncateToTail(text: string, maxChars: number): {
8
+ output: string;
9
+ removed: number;
10
+ };
11
+ export declare function generateChunkId(): string;
12
+ export declare function truncateOutput(text: string, maxOutputTokens?: number, originalCharCount?: number): {
13
+ output: string;
14
+ original_token_count?: number;
15
+ truncated?: true;
16
+ };
17
+ export declare function consumeOutput(session: ExecOutputSessionState, maxOutputTokens?: number): ReturnType<typeof truncateOutput>;
18
+ export declare function peekUnconsumedOutput(session: ExecOutputSessionState, maxOutputTokens?: number): ReturnType<typeof truncateOutput>;
19
+ export declare function peekOutputSince(session: ExecOutputSessionState, baselineOffset: number, maxOutputTokens?: number): ReturnType<typeof truncateOutput>;
@@ -0,0 +1,50 @@
1
+ import type { ShellProcess, ShellProcessBackend } from "./backend.ts";
2
+ export interface ProcessExecSession {
3
+ id: number;
4
+ startup: Promise<void>;
5
+ started: boolean;
6
+ tty: boolean;
7
+ command: string;
8
+ buffer: string;
9
+ bufferStartOffset: number;
10
+ emittedOffset: number;
11
+ outputVersion: number;
12
+ exitCode: number | undefined;
13
+ listeners: Set<() => void>;
14
+ interactive: boolean;
15
+ nextEmptyPollYieldMs?: number | undefined;
16
+ startedAt: number;
17
+ updatedAt: number;
18
+ finalized: boolean;
19
+ exposed: boolean;
20
+ terminating: boolean;
21
+ process?: ShellProcess;
22
+ }
23
+ export interface ProcessSessionHooks {
24
+ isOwned(session: ProcessExecSession): boolean;
25
+ onOutput(session: ProcessExecSession, text: string): void;
26
+ onExit(session: ProcessExecSession): void;
27
+ }
28
+ interface CreateSession {
29
+ id: number;
30
+ input: {
31
+ command: string;
32
+ executionCommand: string;
33
+ executionEnv: NodeJS.ProcessEnv;
34
+ tty?: boolean;
35
+ login?: boolean;
36
+ };
37
+ workdir: string;
38
+ shell: string;
39
+ signal?: AbortSignal;
40
+ hooks: ProcessSessionHooks;
41
+ }
42
+ /** Owns asynchronous startup and per-stream codecs. The manager owns retention and wait policy. */
43
+ export declare function createProcessSessionRuntime(backend: ShellProcessBackend): {
44
+ create: ({ id, input, workdir, shell, signal, hooks, }: CreateSession) => ProcessExecSession;
45
+ waitForStartup: (session: ProcessExecSession, signal?: AbortSignal) => Promise<void>;
46
+ write: (session: ProcessExecSession, chars: string) => Promise<void>;
47
+ terminate: (session: ProcessExecSession) => Promise<void>;
48
+ shutdown: () => Promise<void>;
49
+ };
50
+ export {};
@@ -0,0 +1,14 @@
1
+ import { type ExecOutputSessionState } from "./output.ts";
2
+ import type { ExecSessionSnapshot, UnifiedExecResult } from "./session-store.ts";
3
+ export interface ExecResultSessionState extends ExecOutputSessionState {
4
+ id: number;
5
+ command: string;
6
+ exitCode: number | null | undefined;
7
+ startedAt: number;
8
+ updatedAt: number;
9
+ terminating: boolean;
10
+ }
11
+ export declare function makeExecResult<TSession extends ExecResultSessionState>(session: TSession, waitMs: number, maxOutputTokens: number | undefined, exposeSession: (session: TSession) => void, deleteSessionIfDrained: (sessionId: number) => void): UnifiedExecResult;
12
+ export declare function snapshotSession(session: ExecResultSessionState, maxOutputChars?: number): ExecSessionSnapshot;
13
+ export declare function makeSnapshotResult(session: ExecResultSessionState, waitMs: number, maxOutputTokens?: number, unconsumedOnly?: boolean): UnifiedExecResult;
14
+ export declare function makeSnapshotSince(session: ExecResultSessionState, waitMs: number, baselineOffset: number, maxOutputTokens?: number): UnifiedExecResult;
@@ -0,0 +1,46 @@
1
+ import type { ShellProcessBackend } from "./backend.ts";
2
+ import { type ExecSessionChangeReason, type ExecSessionSnapshot, type UnifiedExecResult } from "./session-store.ts";
3
+ interface ExecCommandInput {
4
+ cmd: string;
5
+ workdir?: string | undefined;
6
+ shell?: string | undefined;
7
+ defaultShell?: string | undefined;
8
+ env?: NodeJS.ProcessEnv | undefined;
9
+ tty?: boolean | undefined;
10
+ yield_time_ms?: number | undefined;
11
+ max_yield_time_ms?: number | undefined;
12
+ max_output_tokens?: number | undefined;
13
+ login?: boolean | undefined;
14
+ wait_until_exit?: boolean | undefined;
15
+ }
16
+ interface WriteStdinInput {
17
+ session_id: number;
18
+ chars?: string | undefined;
19
+ yield_time_ms?: number | undefined;
20
+ max_output_tokens?: number | undefined;
21
+ }
22
+ type ExecSessionUpdateCallback = (result: UnifiedExecResult) => void;
23
+ export interface ExecSessionManager {
24
+ setBaseEnv(env: NodeJS.ProcessEnv): void;
25
+ exec(input: ExecCommandInput, cwd: string, signal?: AbortSignal, onUpdate?: ExecSessionUpdateCallback): Promise<UnifiedExecResult>;
26
+ write(input: WriteStdinInput, signal?: AbortSignal, onUpdate?: ExecSessionUpdateCallback): Promise<UnifiedExecResult>;
27
+ hasSession(sessionId: number): boolean;
28
+ getSessionCommand(sessionId: number): string | undefined;
29
+ listSessions(maxOutputChars?: number): ExecSessionSnapshot[];
30
+ terminateSession(sessionId: number): boolean;
31
+ onSessionChange(listener: (reason: ExecSessionChangeReason) => void): () => void;
32
+ onSessionExit(listener: (sessionId: number, command: string) => void): () => void;
33
+ shutdown(): Promise<void>;
34
+ }
35
+ export interface ExecSessionManagerOptions {
36
+ env?: NodeJS.ProcessEnv | undefined;
37
+ backend: ShellProcessBackend;
38
+ defaultExecYieldTimeMs?: number | undefined;
39
+ defaultWriteYieldTimeMs?: number | undefined;
40
+ minNonInteractiveExecYieldTimeMs?: number | undefined;
41
+ minEmptyWriteYieldTimeMs?: number | undefined;
42
+ maxEmptyWriteYieldTimeMs?: number | undefined;
43
+ maxSessionBufferChars?: number | undefined;
44
+ }
45
+ export declare function createExecSessionManager(options: ExecSessionManagerOptions): ExecSessionManager;
46
+ export {};
@@ -0,0 +1,53 @@
1
+ import type { ProcessExecSession } from "./process-session.ts";
2
+ export type UnifiedExecResult = {
3
+ chunk_id: string;
4
+ wall_time_seconds: number;
5
+ output: string;
6
+ exit_code?: number;
7
+ session_id?: number;
8
+ original_token_count?: number;
9
+ truncated?: true;
10
+ };
11
+ export interface ExecSessionSnapshot {
12
+ id: number;
13
+ command: string;
14
+ running: boolean;
15
+ exitCode?: number | undefined;
16
+ startedAt: number;
17
+ updatedAt: number;
18
+ outputTail: string;
19
+ terminating: boolean;
20
+ }
21
+ export type ExecSessionChangeReason = "start" | "output" | "exit" | "terminate";
22
+ type ExecSession = ProcessExecSession;
23
+ /** Own live visibility, bounded output, termination visibility and process-local completed history. */
24
+ export declare class ExecSessionStore {
25
+ private readonly sessions;
26
+ private readonly commandHistory;
27
+ private readonly completedResults;
28
+ private readonly changeListeners;
29
+ private readonly exitListeners;
30
+ private readonly configuredMaxSessionBufferChars;
31
+ constructor(configuredMaxSessionBufferChars?: number);
32
+ add(session: ExecSession): void;
33
+ get(id: number): ExecSession | undefined;
34
+ remove(id: number): void;
35
+ clear(): void;
36
+ completedPoll(sessionId: number, chars: string, maxOutputTokens?: number): UnifiedExecResult | undefined;
37
+ private rememberCommand;
38
+ private rememberCompletedResult;
39
+ private replayCompletedResult;
40
+ finishResult(session: ExecSession, waitMs: number, maxOutputTokens?: number): UnifiedExecResult;
41
+ notify(session: ExecSession, reason?: ExecSessionChangeReason): void;
42
+ private notifyChanged;
43
+ finalizeSession(session: ExecSession, reason?: ExecSessionChangeReason): void;
44
+ private exposeSession;
45
+ appendOutput(session: ExecSession, text: string): void;
46
+ hasSession(sessionId: number): boolean;
47
+ getSessionCommand(sessionId: number): string | undefined;
48
+ listSessions(maxOutputChars?: number): ExecSessionSnapshot[];
49
+ terminateSession(sessionId: number, terminate: (session: ProcessExecSession) => Promise<void>): boolean;
50
+ onSessionChange(listener: (reason: ExecSessionChangeReason) => void): () => void;
51
+ onSessionExit(listener: (sessionId: number, command: string) => void): () => void;
52
+ }
53
+ export {};
@@ -0,0 +1,4 @@
1
+ export declare const CODEX_FALLBACK_SHELL = "/bin/bash";
2
+ export declare function isFishShell(shell: string | undefined): boolean;
3
+ export declare function getCodexRuntimeShell(shell: string | undefined, platform: string, defaultShell?: string): string;
4
+ export declare function getShellArgs(shell: string, command: string, login: boolean): string[];
@@ -0,0 +1,14 @@
1
+ export declare const MAX_EXEC_YIELD_TIME_MS = 1800000;
2
+ export declare const DEFAULT_EXEC_YIELD_TIME_MS = 10000;
3
+ export declare const DEFAULT_WRITE_YIELD_TIME_MS = 250;
4
+ export declare const DEFAULT_MAX_EMPTY_WRITE_YIELD_TIME_MS = 1800000;
5
+ export declare function resolveShell(shell: string | undefined, platform?: string, defaultShell?: string): string;
6
+ export declare function resolveExecution(requestedShell: string | undefined, command: string, extraEnv: NodeJS.ProcessEnv | undefined, baseEnv: NodeJS.ProcessEnv, platform: string, defaultShell: string): {
7
+ shell: string;
8
+ command: string;
9
+ env: NodeJS.ProcessEnv;
10
+ };
11
+ export declare function normalizeMinNonInteractiveExecYieldTime(value: number | undefined): number;
12
+ export declare function normalizeMinEmptyWriteYieldTime(value: number | undefined): number;
13
+ export declare function clampExecYieldTime(yieldTimeMs: number | undefined, fallback: number, isInteractive: boolean, minNonInteractiveExecYieldTimeMs: number, maxYieldTimeMs?: number): number;
14
+ export declare function clampWriteYieldTime(yieldTimeMs: number | undefined, fallback: number, isEmptyPoll: boolean, minEmptyWriteYieldTimeMs: number, maxEmptyWriteYieldTimeMs: number): number;
@@ -0,0 +1,7 @@
1
+ export interface WaitableSession {
2
+ exitCode: number | null | undefined;
3
+ outputVersion: number;
4
+ listeners: Set<() => void>;
5
+ }
6
+ export declare function registerAbortHandler(signal: AbortSignal | undefined, onAbort: () => void): () => void;
7
+ export declare function waitForExitOrInactivity(session: WaitableSession, idleTimeMs: number, maxWaitMs?: number, signal?: AbortSignal, onUpdate?: (elapsedMs: number) => void): Promise<number>;
@@ -0,0 +1,14 @@
1
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
2
+ import { type ExecSessionManagerOptions } from "./shell/session-manager.ts";
3
+ export type { ShellOutputStream, ShellProcess, ShellProcessBackend, ShellProcessEvents, ShellSpawnRequest, } from "./shell/backend.ts";
4
+ export { createNodeShellBackend, type NodeShellBackendOptions, } from "./shell/node-backend.ts";
5
+ export interface ShellRuntimeOptions extends ExecSessionManagerOptions {
6
+ waitForNonInteractiveExit?: boolean;
7
+ }
8
+ export interface ShellRuntime {
9
+ readonly tools: readonly ToolRegistration[];
10
+ /** Idempotently terminate owned sessions. The Code or Notebook connection owns this call. */
11
+ close(): Promise<void>;
12
+ }
13
+ /** Ordinary Durable registrations shared internally by both public execution modes. */
14
+ export declare function createShellRuntime(options: ShellRuntimeOptions): ShellRuntime;
@@ -0,0 +1,34 @@
1
+ import { type JsonValue } from "@earendil-works/chord";
2
+ import type { TSchema } from "@earendil-works/pi-ai";
3
+ import type { ToolRegistration } from "@earendil-works/pi-durable";
4
+ /** Optional runtime presentation and observation policy on an ordinary registration. */
5
+ export interface ExecutionToolHints {
6
+ readonly usage?: string;
7
+ readonly output?: string;
8
+ readonly deferLoading?: boolean;
9
+ readonly yieldTimeMs?: number;
10
+ readonly inputSchema?: JsonValue;
11
+ /** Empty calls return help without performing an operation. Never inferred from schema shape. */
12
+ readonly discovery?: "help";
13
+ /** Keep the tool on the provider surface and prohibit calls from execution cells. */
14
+ readonly nativeOnly?: boolean;
15
+ }
16
+ export type ExecutionToolRegistration<T extends TSchema = TSchema, D extends JsonValue = JsonValue> = ToolRegistration<T, D> & {
17
+ readonly executionHints?: ExecutionToolHints;
18
+ };
19
+ interface ExecutionToolContract {
20
+ readonly name: string;
21
+ readonly description: string;
22
+ readonly usage: string;
23
+ readonly output?: string;
24
+ readonly inputSchema: JsonValue;
25
+ readonly deferLoading: boolean;
26
+ readonly nativeOnly: boolean;
27
+ readonly discovery?: "help";
28
+ readonly yieldTimeMs?: number;
29
+ readonly help: string;
30
+ readonly prompt: string;
31
+ }
32
+ /** Validate ordinary registration metadata before presentation or execution policy uses it. */
33
+ export declare function readToolContract(tool: ToolRegistration | ExecutionToolRegistration): ExecutionToolContract;
34
+ export {};
@@ -0,0 +1,11 @@
1
+ import { type ConversationId, type TaskId } from "@earendil-works/pi-durable";
2
+ /** Admission provenance, not authorization: consumers must still verify the live originating slot. */
3
+ export type ToolOrigin = {
4
+ conversationId: ConversationId;
5
+ taskId: TaskId;
6
+ callId: string;
7
+ };
8
+ /** Host-written metadata. Never populated from tool arguments or inferred from the latest turn. */
9
+ export declare const ToolOriginDoc: import("@earendil-works/pi-durable").TaskDocToken<{
10
+ origin?: ToolOrigin;
11
+ }>;
@@ -0,0 +1,6 @@
1
+ interface ToolYieldHint {
2
+ readonly name: string;
3
+ readonly yieldTimeMs?: number;
4
+ }
5
+ export declare function directToolYieldTime(code: string, tools: readonly ToolYieldHint[]): number | null;
6
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { ToolExecutionResult } from "@earendil-works/pi-durable";
2
+ /** One JS value projection for every ordinary registration. Images remain usable with image(). */
3
+ export declare function toolValue(result: ToolExecutionResult): unknown;