@howaboua/pi-durable-code 0.0.0-stage → 0.9.1
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/LICENSE +21 -0
- package/NOTICE +251 -0
- package/README.md +93 -2
- package/dist/code/src/binary.d.ts +6 -0
- package/dist/code/src/cell-output.d.ts +33 -0
- package/dist/code/src/engine.d.ts +16 -0
- package/dist/code/src/history.d.ts +6 -0
- package/dist/code/src/host-assets.d.ts +4 -0
- package/dist/code/src/host-connection.d.ts +29 -0
- package/dist/code/src/host-process.d.ts +21 -0
- package/dist/code/src/host-protocol.d.ts +54 -0
- package/dist/code/src/host-runtime.d.ts +21 -0
- package/dist/code/src/host-session.d.ts +24 -0
- package/dist/code/src/index.d.ts +32 -0
- package/dist/code/src/install-host.d.ts +7 -0
- package/dist/code/src/presentation.d.ts +22 -0
- package/dist/code/src/result.d.ts +4 -0
- package/dist/code/src/runtime-contract.d.ts +24 -0
- package/dist/code/src/runtime-response.d.ts +2 -0
- package/dist/code/src/runtime-tools.d.ts +7 -0
- package/dist/execution/src/cell-contract.d.ts +49 -0
- package/dist/execution/src/cell-observation.d.ts +7 -0
- package/dist/execution/src/cell-progress.d.ts +4 -0
- package/dist/execution/src/cell-task.d.ts +17 -0
- package/dist/execution/src/cell-tools.d.ts +8 -0
- package/dist/execution/src/cells.d.ts +14 -0
- package/dist/execution/src/command-backend.d.ts +22 -0
- package/dist/execution/src/controls.d.ts +3 -0
- package/dist/execution/src/custom-command-config.d.ts +21 -0
- package/dist/execution/src/custom-commands.d.ts +62 -0
- package/dist/execution/src/exec-source.d.ts +21 -0
- package/dist/execution/src/forwarded-tools.d.ts +21 -0
- package/dist/execution/src/forwarding-hook.d.ts +6 -0
- package/dist/execution/src/forwarding.d.ts +15 -0
- package/dist/execution/src/history.d.ts +14 -0
- package/dist/execution/src/index.d.ts +6 -0
- package/dist/execution/src/invocation-state.d.ts +26 -0
- package/dist/execution/src/invocation.d.ts +35 -0
- package/dist/execution/src/native-tools.d.ts +11 -0
- package/dist/execution/src/nested-call.d.ts +26 -0
- package/dist/execution/src/nested-result.d.ts +8 -0
- package/dist/execution/src/nested.d.ts +3 -0
- package/dist/execution/src/output.d.ts +48 -0
- package/dist/execution/src/presentation.d.ts +59 -0
- package/dist/execution/src/progress.d.ts +23 -0
- package/dist/execution/src/projection.d.ts +5 -0
- package/dist/execution/src/shell/backend.d.ts +28 -0
- package/dist/execution/src/shell/format.d.ts +2 -0
- package/dist/execution/src/shell/node-backend.d.ts +9 -0
- package/dist/execution/src/shell/output.d.ts +19 -0
- package/dist/execution/src/shell/process-session.d.ts +50 -0
- package/dist/execution/src/shell/results.d.ts +14 -0
- package/dist/execution/src/shell/session-manager.d.ts +46 -0
- package/dist/execution/src/shell/session-store.d.ts +53 -0
- package/dist/execution/src/shell/shell-args.d.ts +4 -0
- package/dist/execution/src/shell/shell.d.ts +14 -0
- package/dist/execution/src/shell/wait.d.ts +7 -0
- package/dist/execution/src/shell.d.ts +14 -0
- package/dist/execution/src/tool-contract.d.ts +34 -0
- package/dist/execution/src/tool-origin.d.ts +11 -0
- package/dist/execution/src/tool-source.d.ts +6 -0
- package/dist/execution/src/tool-value.d.ts +3 -0
- package/dist/execution/src/wait-session.d.ts +6 -0
- package/dist/history.js +315 -0
- package/dist/index.js +5063 -0
- package/dist/presentation.js +198 -0
- package/package.json +54 -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,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
|
+
import type { Context } from "@earendil-works/chord";
|
|
2
|
+
import type { TaskId, ToolExecutionApi, ToolExecutionResult } from "@earendil-works/pi-durable";
|
|
3
|
+
import type { CellCoordinatorOptions, CellObservation } from "./cell-contract.ts";
|
|
4
|
+
import type { createNestedToolTask } from "./nested.ts";
|
|
5
|
+
/** Poll a mistaken shell handle through the selected registration, never by shell internals. */
|
|
6
|
+
export declare function recoverWaitSession(cellId: TaskId<ToolExecutionResult>, yieldTimeMs: number, maxTokens: number, api: ToolExecutionApi, context: Context, nestedTask: ReturnType<typeof createNestedToolTask>, cancelTask: CellCoordinatorOptions["cancelTask"]): Promise<CellObservation | undefined>;
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
// packages/execution/src/exec-source.ts
|
|
2
|
+
var MAX_CODE_MODE_OUTPUT_TOKENS = 1e5;
|
|
3
|
+
var CODE_MODE_EXEC_GRAMMAR = String.raw`
|
|
4
|
+
start: pragma_source | plain_source
|
|
5
|
+
pragma_source: PRAGMA_LINE NEWLINE SOURCE
|
|
6
|
+
plain_source: SOURCE
|
|
7
|
+
|
|
8
|
+
PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/
|
|
9
|
+
NEWLINE: /\r?\n/
|
|
10
|
+
SOURCE: /[\s\S]+/
|
|
11
|
+
`;
|
|
12
|
+
|
|
13
|
+
// packages/execution/src/forwarding.ts
|
|
14
|
+
import { copyJson as copyJson2 } from "@earendil-works/chord";
|
|
15
|
+
import {
|
|
16
|
+
LiveDoc,
|
|
17
|
+
NestedCallDoc,
|
|
18
|
+
ToolTask
|
|
19
|
+
} from "@earendil-works/pi-durable";
|
|
20
|
+
|
|
21
|
+
// packages/execution/src/invocation-state.ts
|
|
22
|
+
import {
|
|
23
|
+
copyJson
|
|
24
|
+
} from "@earendil-works/chord";
|
|
25
|
+
import {
|
|
26
|
+
defineDoc
|
|
27
|
+
} from "@earendil-works/pi-durable";
|
|
28
|
+
var InvocationDoc = defineDoc({
|
|
29
|
+
kind: "howaboua.execution.invocation",
|
|
30
|
+
version: 2,
|
|
31
|
+
scope: "task",
|
|
32
|
+
checkpointWhen: () => false,
|
|
33
|
+
initial: () => ({ result: {} }),
|
|
34
|
+
migrate: (value) => ({
|
|
35
|
+
...value,
|
|
36
|
+
result: storeResult(readStoredResult(value["result"]))
|
|
37
|
+
})
|
|
38
|
+
});
|
|
39
|
+
function readStoredResult(result) {
|
|
40
|
+
if (result.output !== undefined || !("content" in result))
|
|
41
|
+
return result;
|
|
42
|
+
const { content, ...rest } = result;
|
|
43
|
+
return {
|
|
44
|
+
...rest,
|
|
45
|
+
output: content
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function storeResult(result) {
|
|
49
|
+
return copyJson(result, { omitUndefinedProperties: true });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// packages/execution/src/output.ts
|
|
53
|
+
var encoder = new TextEncoder;
|
|
54
|
+
var decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
55
|
+
|
|
56
|
+
// packages/execution/src/forwarding.ts
|
|
57
|
+
var bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
|
|
58
|
+
function boundForwardedToolCalls(value, budget) {
|
|
59
|
+
const calls = [];
|
|
60
|
+
let remaining = budget;
|
|
61
|
+
let omittedCalls = value.omittedCalls;
|
|
62
|
+
for (const source of value.calls) {
|
|
63
|
+
let call = source;
|
|
64
|
+
if (bytes(call) > remaining && call.result !== null) {
|
|
65
|
+
call = {
|
|
66
|
+
...call,
|
|
67
|
+
result: null,
|
|
68
|
+
omittedFields: [...call.omittedFields, "result"]
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
if (bytes(call) > remaining && call.arguments !== undefined) {
|
|
72
|
+
const { arguments: _arguments, ...rest } = call;
|
|
73
|
+
call = { ...rest, omittedFields: [...call.omittedFields, "arguments"] };
|
|
74
|
+
}
|
|
75
|
+
const cost = bytes(call);
|
|
76
|
+
if (cost > remaining)
|
|
77
|
+
omittedCalls++;
|
|
78
|
+
else {
|
|
79
|
+
calls.push(call);
|
|
80
|
+
remaining -= cost;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { ...value, calls, omittedCalls };
|
|
84
|
+
}
|
|
85
|
+
function forwardedStatus(result, fallback) {
|
|
86
|
+
if (result.diagnostics?.some((item) => item.code === "interrupted"))
|
|
87
|
+
return "interrupted";
|
|
88
|
+
if (result.diagnostics?.some((item) => item.code === "aborted" || item.code === "abandoned"))
|
|
89
|
+
return "aborted";
|
|
90
|
+
return fallback;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// packages/execution/src/nested-result.ts
|
|
94
|
+
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
95
|
+
import {
|
|
96
|
+
defineEntry,
|
|
97
|
+
UsageDoc
|
|
98
|
+
} from "@earendil-works/pi-durable";
|
|
99
|
+
|
|
100
|
+
// packages/execution/src/invocation.ts
|
|
101
|
+
import { copyJson as copyJson4 } from "@earendil-works/chord";
|
|
102
|
+
import { awaitWithContext } from "@earendil-works/chord/context";
|
|
103
|
+
|
|
104
|
+
// packages/execution/src/native-tools.ts
|
|
105
|
+
import { copyJson as copyJson3 } from "@earendil-works/chord";
|
|
106
|
+
import { withoutAbortSignal } from "@earendil-works/chord/context";
|
|
107
|
+
import {
|
|
108
|
+
LiveDoc as LiveDoc2,
|
|
109
|
+
NestedCallDoc as NestedCallDoc2,
|
|
110
|
+
ToolTask as ToolTask2
|
|
111
|
+
} from "@earendil-works/pi-durable";
|
|
112
|
+
import { Equal } from "typebox/value";
|
|
113
|
+
|
|
114
|
+
// packages/execution/src/progress.ts
|
|
115
|
+
var PROGRESS_BYTES_PER_SECOND = 100 * 1024;
|
|
116
|
+
|
|
117
|
+
// packages/execution/src/tool-origin.ts
|
|
118
|
+
import {
|
|
119
|
+
defineDoc as defineDoc2
|
|
120
|
+
} from "@earendil-works/pi-durable";
|
|
121
|
+
var ToolOriginDoc = defineDoc2({
|
|
122
|
+
kind: "howaboua.tool-origin",
|
|
123
|
+
version: 1,
|
|
124
|
+
scope: "task",
|
|
125
|
+
checkpointWhen: () => false,
|
|
126
|
+
initial: () => ({})
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// packages/execution/src/nested-result.ts
|
|
130
|
+
var NestedResultEntry = defineEntry("howaboua.execution.nested-result");
|
|
131
|
+
|
|
132
|
+
// packages/execution/src/presentation.ts
|
|
133
|
+
function object(value) {
|
|
134
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
|
|
135
|
+
throw new TypeError("Expected execution presentation object");
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
function string(value) {
|
|
139
|
+
if (typeof value !== "string")
|
|
140
|
+
throw new TypeError("Expected string");
|
|
141
|
+
return value;
|
|
142
|
+
}
|
|
143
|
+
function json(value, ancestors = new Set) {
|
|
144
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
145
|
+
return value;
|
|
146
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
147
|
+
return value;
|
|
148
|
+
if (typeof value !== "object" || ancestors.has(value))
|
|
149
|
+
throw new TypeError("Expected finite, acyclic JSON details");
|
|
150
|
+
ancestors.add(value);
|
|
151
|
+
try {
|
|
152
|
+
if (!Array.isArray(value))
|
|
153
|
+
object(value);
|
|
154
|
+
return Array.isArray(value) ? value.map((item) => json(item, ancestors)) : Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
155
|
+
key,
|
|
156
|
+
json(item, ancestors)
|
|
157
|
+
]));
|
|
158
|
+
} finally {
|
|
159
|
+
ancestors.delete(value);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function parseExecutionResultReceipt(value) {
|
|
163
|
+
if (value === null)
|
|
164
|
+
return null;
|
|
165
|
+
const fields = object(value);
|
|
166
|
+
const content = fields["content"] === undefined ? [] : fields["content"];
|
|
167
|
+
const diagnostics = fields["diagnostics"] === undefined ? [] : fields["diagnostics"];
|
|
168
|
+
const isError = fields["isError"] === undefined ? false : fields["isError"];
|
|
169
|
+
if (!Array.isArray(content) || !Array.isArray(diagnostics) || typeof isError !== "boolean")
|
|
170
|
+
throw new TypeError("Invalid execution result receipt");
|
|
171
|
+
return {
|
|
172
|
+
content: content.map((value) => {
|
|
173
|
+
const item = object(value);
|
|
174
|
+
if (item["type"] === "text")
|
|
175
|
+
return { type: "text", text: string(item["text"]) };
|
|
176
|
+
if (item["type"] === "image") {
|
|
177
|
+
const mimeType = string(item["mimeType"]);
|
|
178
|
+
const data = string(item["data"]);
|
|
179
|
+
if (!/^image\/[A-Za-z0-9][A-Za-z0-9.+-]*$/.test(mimeType) || data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data))
|
|
180
|
+
throw new TypeError("Invalid execution image");
|
|
181
|
+
return { type: "image", data, mimeType };
|
|
182
|
+
}
|
|
183
|
+
throw new TypeError("Invalid execution content type");
|
|
184
|
+
}),
|
|
185
|
+
isError,
|
|
186
|
+
details: json(fields["details"] ?? null),
|
|
187
|
+
diagnostics: diagnostics.map((value) => {
|
|
188
|
+
const item = object(value);
|
|
189
|
+
const severity = item["severity"];
|
|
190
|
+
if (severity !== "info" && severity !== "warn" && severity !== "error")
|
|
191
|
+
throw new TypeError("Invalid execution diagnostic severity");
|
|
192
|
+
return {
|
|
193
|
+
severity,
|
|
194
|
+
message: string(item["message"]),
|
|
195
|
+
...item["code"] === undefined ? {} : { code: string(item["code"]) }
|
|
196
|
+
};
|
|
197
|
+
})
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// packages/execution/src/history.ts
|
|
202
|
+
function object2(value) {
|
|
203
|
+
if (value === null || value === undefined || typeof value !== "object" || Array.isArray(value))
|
|
204
|
+
throw new TypeError("Invalid historical execution record");
|
|
205
|
+
return value;
|
|
206
|
+
}
|
|
207
|
+
function taskId(value) {
|
|
208
|
+
const id = Number(value);
|
|
209
|
+
if (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(id))
|
|
210
|
+
throw new TypeError("Invalid historical execution cell ID");
|
|
211
|
+
return id;
|
|
212
|
+
}
|
|
213
|
+
function executionHistory(mode) {
|
|
214
|
+
return async function readForwardedToolCalls(harness, request, context) {
|
|
215
|
+
const maxTokens = request.maxOutputTokens ?? 1e4;
|
|
216
|
+
if (!Number.isSafeInteger(maxTokens) || maxTokens < 1 || maxTokens > MAX_CODE_MODE_OUTPUT_TOKENS)
|
|
217
|
+
throw new TypeError("Invalid historical execution output budget");
|
|
218
|
+
const requested = new Map(request.cellIds.map((id) => [taskId(id), id]));
|
|
219
|
+
const results = new Map;
|
|
220
|
+
if (requested.size === 0)
|
|
221
|
+
return results;
|
|
222
|
+
const conversation = await harness.conversation(request.conversationId, context);
|
|
223
|
+
if (conversation === undefined)
|
|
224
|
+
throw new Error("Historical execution conversation is unavailable");
|
|
225
|
+
const cells = await harness.commit(async (tx) => {
|
|
226
|
+
const ancestors = new Set;
|
|
227
|
+
let current = request.conversationId;
|
|
228
|
+
while (current !== undefined) {
|
|
229
|
+
if (ancestors.has(current))
|
|
230
|
+
throw new Error("Cyclic conversation ancestry");
|
|
231
|
+
ancestors.add(current);
|
|
232
|
+
current = (await tx.conversation(current))?.parent?.conversationId;
|
|
233
|
+
}
|
|
234
|
+
const cells = new Map;
|
|
235
|
+
for (const [id, cellId] of requested) {
|
|
236
|
+
const record = await tx.task(id);
|
|
237
|
+
if (record?.kind === `howaboua.execution.cell.${mode}` && ancestors.has(record.conversationId))
|
|
238
|
+
cells.set(id, { cellId, conversationId: record.conversationId });
|
|
239
|
+
}
|
|
240
|
+
return cells;
|
|
241
|
+
}, context);
|
|
242
|
+
if (cells.size === 0)
|
|
243
|
+
return results;
|
|
244
|
+
const tail = (await conversation.entries({ order: "descending" }, 1, undefined, context)).items[0];
|
|
245
|
+
if (tail === undefined)
|
|
246
|
+
return results;
|
|
247
|
+
const minimum = Math.min(...cells.keys());
|
|
248
|
+
if (minimum > tail.id)
|
|
249
|
+
return results;
|
|
250
|
+
let cursor;
|
|
251
|
+
do {
|
|
252
|
+
const page = await conversation.entries({ minEntryId: minimum, maxEntryId: tail.id, order: "ascending" }, 100, cursor, context);
|
|
253
|
+
for (const entry of page.items) {
|
|
254
|
+
if (!NestedResultEntry.is(entry))
|
|
255
|
+
continue;
|
|
256
|
+
const data = entry.data;
|
|
257
|
+
const id = data["taskId"];
|
|
258
|
+
if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0 || entry.byTaskId !== id)
|
|
259
|
+
continue;
|
|
260
|
+
const record = await harness.getTask(id, context);
|
|
261
|
+
if (record?.kind !== `howaboua.execution.nested-tool.${mode}` || record.owner === undefined || record.state.status !== "terminal")
|
|
262
|
+
continue;
|
|
263
|
+
const cell = cells.get(record.owner);
|
|
264
|
+
if (cell === undefined || record.conversationId !== cell.conversationId || entry.conversationId !== cell.conversationId)
|
|
265
|
+
continue;
|
|
266
|
+
const input = object2(record.input);
|
|
267
|
+
const parent = object2(input["parent"]);
|
|
268
|
+
const callId = `nested-${id}`;
|
|
269
|
+
if (parent["taskId"] !== record.owner || typeof parent["callId"] !== "string" || !parent["callId"] || typeof input["name"] !== "string" || !input["name"] || data["name"] !== input["name"] || data["callId"] !== callId)
|
|
270
|
+
throw new TypeError("Historical execution audit does not match its task admission");
|
|
271
|
+
const intent = data["intent"] === undefined ? undefined : object2(data["intent"]);
|
|
272
|
+
const args = intent === undefined ? data["arguments"] : intent["arguments"];
|
|
273
|
+
if (args === undefined)
|
|
274
|
+
throw new TypeError("Historical execution arguments are unavailable");
|
|
275
|
+
const stored = object2(data["result"]);
|
|
276
|
+
const receipt = parseExecutionResultReceipt({
|
|
277
|
+
content: stored["output"] ?? stored["content"] ?? [],
|
|
278
|
+
isError: stored["isError"] ?? false,
|
|
279
|
+
details: stored["details"] ?? null,
|
|
280
|
+
diagnostics: stored["diagnostics"] ?? []
|
|
281
|
+
});
|
|
282
|
+
if (receipt === null)
|
|
283
|
+
throw new TypeError("Historical execution result is unavailable");
|
|
284
|
+
const outcome = record.state.outcome;
|
|
285
|
+
const call = {
|
|
286
|
+
callId,
|
|
287
|
+
parentCallId: parent["callId"],
|
|
288
|
+
name: input["name"],
|
|
289
|
+
arguments: args,
|
|
290
|
+
status: forwardedStatus({ diagnostics: receipt.diagnostics }, outcome.status === "completed" ? "completed" : outcome.status === "aborted" ? "aborted" : "failed"),
|
|
291
|
+
result: receipt,
|
|
292
|
+
omittedFields: []
|
|
293
|
+
};
|
|
294
|
+
const previous = results.get(cell.cellId) ?? {
|
|
295
|
+
version: 1,
|
|
296
|
+
cellId: cell.cellId,
|
|
297
|
+
calls: [],
|
|
298
|
+
omittedCalls: 0
|
|
299
|
+
};
|
|
300
|
+
if (previous.calls.some((item) => item.callId === callId))
|
|
301
|
+
throw new TypeError("Duplicate historical execution result");
|
|
302
|
+
const calls = [...previous.calls, call].sort((left, right) => Number(left.callId.slice("nested-".length)) - Number(right.callId.slice("nested-".length)));
|
|
303
|
+
results.set(cell.cellId, boundForwardedToolCalls({ ...previous, calls }, maxTokens * 4));
|
|
304
|
+
}
|
|
305
|
+
cursor = page.next;
|
|
306
|
+
} while (cursor !== undefined);
|
|
307
|
+
return results;
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// packages/code/src/history.ts
|
|
312
|
+
var readForwardedToolCalls = executionHistory("code");
|
|
313
|
+
export {
|
|
314
|
+
readForwardedToolCalls
|
|
315
|
+
};
|