@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.2
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/README.md +1403 -2
- package/build-internals.ts +25 -0
- package/caller/agent-launch.ts +60 -0
- package/client.tsx +498 -0
- package/component-actions.ts +327 -0
- package/component-alerts.ts +136 -0
- package/component-attributes.ts +340 -0
- package/component-parts.tsx +1177 -0
- package/core-contracts/auth.ts +40 -0
- package/package.json +98 -4
- package/quit.ts +58 -0
- package/regions.tsx +94 -0
- package/screen-search.ts +211 -0
- package/send-file.ts +175 -0
- package/server-build-internals.ts +11 -0
- package/solid.ts +132 -0
- package/src/agent-command.ts +48 -0
- package/src/agent-info-cache.ts +34 -0
- package/src/agent-reports.ts +140 -0
- package/src/agent-turn.ts +289 -0
- package/src/api.ts +174 -0
- package/src/auth.ts +39 -0
- package/src/call-error.ts +37 -0
- package/src/caller-storage.ts +32 -0
- package/src/client.ts +163 -0
- package/src/database.ts +322 -0
- package/src/functions.ts +726 -0
- package/src/hooks.ts +141 -0
- package/src/host.ts +211 -0
- package/src/http-action.ts +55 -0
- package/src/index.ts +126 -0
- package/src/internal/contracts.ts +260 -0
- package/src/internal/machine-scope.ts +21 -0
- package/src/local.ts +22 -0
- package/src/plugin.ts +162 -0
- package/src/points.ts +79 -0
- package/src/protocol.ts +64 -0
- package/src/schema.ts +136 -0
- package/src/storage.ts +193 -0
- package/src/thread-context.ts +42 -0
- package/src/transport.ts +421 -0
- package/src/triggers.ts +87 -0
- package/src/unstable.ts +66 -0
- package/src/validators.ts +248 -0
- package/src/values.ts +98 -0
- package/src/visibility.ts +8 -0
- package/src/websocket-transport.ts +91 -0
- package/src/window-state-protocol.ts +7 -0
- package/src/within.ts +24 -0
- package/src/worker-limits.ts +5 -0
- package/tools/bundle.mjs +490 -0
- package/tools/client-entry.mjs +10 -0
- package/tools/contracts.mjs +254 -0
- package/tools/http-actions.mjs +42 -0
- package/tools/placement.mjs +535 -0
- package/tools/plugin-boundary.mjs +592 -0
- package/tools/plugin-compiler.mjs +125 -0
- package/tools/plugin-descriptor.ts +75 -0
- package/tools/points.mjs +340 -0
- package/tools/result-validator.mjs +83 -0
- package/tools/server-builtins.mjs +82 -0
- package/tools/server-files.mjs +34 -0
- package/tools/table-references.mjs +98 -0
- package/tools/worker.mjs +110 -0
- package/tsconfig.plugin-server.json +12 -0
- package/tsconfig.plugin-window.json +15 -0
- package/view.ts +27 -0
- package/web.d.ts +6 -0
- package/window-state-host.ts +228 -0
- package/window-state.ts +43 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Internal interface for the Bun artifact builder's server-side compilation.
|
|
2
|
+
export { declaresAccessTo } from "./src/plugin.ts";
|
|
3
|
+
export { contractDeclarations, contractEntry } from "./tools/contracts.mjs";
|
|
4
|
+
export { httpActionEntry } from "./tools/http-actions.mjs";
|
|
5
|
+
export { functionPlacement, lanes, moduleName, runnerFunction, runnerProvider } from "./tools/placement.mjs";
|
|
6
|
+
export {
|
|
7
|
+
assertPluginResolution,
|
|
8
|
+
checkPluginImports,
|
|
9
|
+
parsePluginSpecifier,
|
|
10
|
+
pluginReferenceSource,
|
|
11
|
+
} from "./tools/plugin-boundary.mjs";
|
package/solid.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/** Optional Solid integration lives outside portable src, so backend bundles and
|
|
2
|
+
* their checked ES2022-only type graph never depend on a UI runtime.
|
|
3
|
+
* Each reactive argument change owns exactly one live subscription. */
|
|
4
|
+
import {
|
|
5
|
+
createComponent,
|
|
6
|
+
createContext,
|
|
7
|
+
createEffect,
|
|
8
|
+
createMemo,
|
|
9
|
+
createSignal,
|
|
10
|
+
getOwner,
|
|
11
|
+
runWithOwner,
|
|
12
|
+
useContext,
|
|
13
|
+
type Accessor,
|
|
14
|
+
type ContextProviderComponent,
|
|
15
|
+
} from "solid-js";
|
|
16
|
+
import type { FunctionReference } from "./src/api";
|
|
17
|
+
import type { TokamaqClient } from "./src/client";
|
|
18
|
+
import { authCaller } from "./src/auth";
|
|
19
|
+
import type { AuthContext, Device, User } from "./src/functions";
|
|
20
|
+
|
|
21
|
+
export interface QueryState<T> {
|
|
22
|
+
data: Accessor<T | undefined>;
|
|
23
|
+
loading: Accessor<boolean>;
|
|
24
|
+
error: Accessor<Error | undefined>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function useQuery<A, R>(
|
|
28
|
+
client: TokamaqClient,
|
|
29
|
+
reference: FunctionReference<"query", A, R>,
|
|
30
|
+
args: Accessor<NoInfer<A>>,
|
|
31
|
+
): QueryState<R> {
|
|
32
|
+
const [data, setData] = createSignal<R | undefined>(undefined, { ownedWrite: true });
|
|
33
|
+
const [loading, setLoading] = createSignal(true, { ownedWrite: true });
|
|
34
|
+
const [error, setError] = createSignal<Error | undefined>(undefined, { ownedWrite: true });
|
|
35
|
+
|
|
36
|
+
createEffect(args, (input) => {
|
|
37
|
+
let active = true;
|
|
38
|
+
setData(undefined);
|
|
39
|
+
setError(undefined);
|
|
40
|
+
setLoading(true);
|
|
41
|
+
try {
|
|
42
|
+
const stop = client.subscribe(reference, input, (event) => {
|
|
43
|
+
if (!active) return;
|
|
44
|
+
if ("value" in event) {
|
|
45
|
+
setData(() => event.value);
|
|
46
|
+
setError(undefined);
|
|
47
|
+
} else setError(event.error);
|
|
48
|
+
setLoading(false);
|
|
49
|
+
});
|
|
50
|
+
return () => {
|
|
51
|
+
active = false;
|
|
52
|
+
stop();
|
|
53
|
+
};
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
active = false;
|
|
56
|
+
setError(cause instanceof Error ? cause : new Error(String(cause)));
|
|
57
|
+
setLoading(false);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
return { data, loading, error };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type LiveCaller = User & { readonly device: Device };
|
|
64
|
+
const ConnectedClient = createContext<TokamaqClient | null>(null);
|
|
65
|
+
const CallerContext = createContext<() => LiveCaller>();
|
|
66
|
+
|
|
67
|
+
const ClientProvider: ContextProviderComponent<TokamaqClient> = (props) => {
|
|
68
|
+
const owner = getOwner();
|
|
69
|
+
const client = props.value;
|
|
70
|
+
let caller: LiveCaller | undefined;
|
|
71
|
+
return createComponent(ConnectedClient, {
|
|
72
|
+
value: client,
|
|
73
|
+
get children() {
|
|
74
|
+
return createComponent(CallerContext, {
|
|
75
|
+
// A read in JSX can re-run. Own the subscription above consumers so
|
|
76
|
+
// they share the object and it lives until the provider is disposed.
|
|
77
|
+
value: () => (caller ??= runWithOwner(owner, () => liveCaller(client))),
|
|
78
|
+
get children() {
|
|
79
|
+
return props.children;
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** The shell supplies its already-connected client; plugins never own sockets. */
|
|
87
|
+
// Copy Solid's context ID and default value so useContext still reads ConnectedClient.
|
|
88
|
+
export const ClientContext = Object.assign(ClientProvider, ConnectedClient);
|
|
89
|
+
export function useClient(): TokamaqClient {
|
|
90
|
+
const client = useContext(ClientContext);
|
|
91
|
+
if (!client) throw new Error("Plugin UI requires the shell client");
|
|
92
|
+
return client;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export const auth = Object.freeze({
|
|
96
|
+
/** Get a live user and device. Reading their fields can suspend until loaded. */
|
|
97
|
+
me(): LiveCaller {
|
|
98
|
+
useClient();
|
|
99
|
+
return useContext(CallerContext)();
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
function liveCaller(client: TokamaqClient): LiveCaller {
|
|
104
|
+
const state = useQuery(client, authCaller, () => ({}));
|
|
105
|
+
// The subscription updates the memo when identity arrives. Until then,
|
|
106
|
+
// Solid can show a loading fallback without inventing an id or role.
|
|
107
|
+
const pending = new Promise<AuthContext>(() => {});
|
|
108
|
+
const caller = createMemo<AuthContext>(() => {
|
|
109
|
+
const error = state.error();
|
|
110
|
+
if (error) throw error;
|
|
111
|
+
return state.data() ?? pending;
|
|
112
|
+
});
|
|
113
|
+
return Object.freeze({
|
|
114
|
+
get id() {
|
|
115
|
+
return caller().user.id;
|
|
116
|
+
},
|
|
117
|
+
get name() {
|
|
118
|
+
return caller().user.name;
|
|
119
|
+
},
|
|
120
|
+
get role() {
|
|
121
|
+
return caller().user.role;
|
|
122
|
+
},
|
|
123
|
+
device: Object.freeze({
|
|
124
|
+
get id() {
|
|
125
|
+
return caller().device.id;
|
|
126
|
+
},
|
|
127
|
+
get name() {
|
|
128
|
+
return caller().device.name;
|
|
129
|
+
},
|
|
130
|
+
}),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { CallerActionContext } from "./functions";
|
|
2
|
+
import type { RunningProcess } from "./local";
|
|
3
|
+
import { TIMED_OUT, within } from "./within";
|
|
4
|
+
|
|
5
|
+
/** A short CLI probe. Missing, a real exit, and no answer are distinct. */
|
|
6
|
+
export async function agentCommand(
|
|
7
|
+
ctx: CallerActionContext,
|
|
8
|
+
[name, ...args]: ["claude" | "codex", ...string[]],
|
|
9
|
+
timeout: number,
|
|
10
|
+
env?: Readonly<Record<string, string>>,
|
|
11
|
+
): Promise<{ stdout: string; code: number } | "missing" | undefined> {
|
|
12
|
+
if (timeout <= 0) return;
|
|
13
|
+
const notFound = new RegExp(`^tokamaq-program: (?:line )?(?:\\d+: )?exec: ${name}: not found$`);
|
|
14
|
+
let program: RunningProcess | undefined;
|
|
15
|
+
let finished = false;
|
|
16
|
+
try {
|
|
17
|
+
const child = (program = ctx.proc([name, ...args], env === undefined ? undefined : { env }));
|
|
18
|
+
child.closeInput();
|
|
19
|
+
const result = await within(
|
|
20
|
+
Promise.all([
|
|
21
|
+
child.exited,
|
|
22
|
+
(async () => {
|
|
23
|
+
let output = "";
|
|
24
|
+
for await (const line of child.stdout) {
|
|
25
|
+
output += line + "\n";
|
|
26
|
+
if (output.length > 64 * 1024) throw new Error("Agent probe output exceeded 64 KiB");
|
|
27
|
+
}
|
|
28
|
+
return output.trim();
|
|
29
|
+
})(),
|
|
30
|
+
(async () => {
|
|
31
|
+
let missing = false;
|
|
32
|
+
for await (const line of child.stderr) missing ||= notFound.test(line);
|
|
33
|
+
return missing;
|
|
34
|
+
})(),
|
|
35
|
+
]),
|
|
36
|
+
timeout,
|
|
37
|
+
);
|
|
38
|
+
if (result === TIMED_OUT) return;
|
|
39
|
+
finished = true;
|
|
40
|
+
const [code, stdout, missing] = result;
|
|
41
|
+
return code === 127 && missing ? "missing" : { code, stdout };
|
|
42
|
+
} catch (error) {
|
|
43
|
+
// Windows uses the executable directly.
|
|
44
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return "missing";
|
|
45
|
+
} finally {
|
|
46
|
+
program?.stop(finished ? undefined : "SIGKILL");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Keep positive discovery answers briefly; never hide a fresh install or sign-in. */
|
|
2
|
+
export const AGENT_INFO_MAX_AGE_MS = 15_000;
|
|
3
|
+
|
|
4
|
+
export function agentInfoCache<Context, Info extends { installed: boolean; signedIn: boolean }>(
|
|
5
|
+
probe: (ctx: Context) => Promise<Info>,
|
|
6
|
+
revision: () => Promise<string>,
|
|
7
|
+
) {
|
|
8
|
+
let cached: { revision: string; until: number; info: Info } | undefined;
|
|
9
|
+
let generation = 0;
|
|
10
|
+
return {
|
|
11
|
+
async read(
|
|
12
|
+
ctx: Context,
|
|
13
|
+
{ fresh = false }: { fresh?: boolean } = {},
|
|
14
|
+
): Promise<Info & { cacheUntil?: number }> {
|
|
15
|
+
if (fresh) {
|
|
16
|
+
generation++;
|
|
17
|
+
cached = undefined;
|
|
18
|
+
}
|
|
19
|
+
const current = await revision();
|
|
20
|
+
if (!fresh && cached?.revision === current && cached.until > Date.now())
|
|
21
|
+
return { ...cached.info, cacheUntil: cached.until };
|
|
22
|
+
const request = ++generation;
|
|
23
|
+
const info = await probe(ctx);
|
|
24
|
+
if (!info.installed || !info.signedIn || request !== generation) return info;
|
|
25
|
+
const until = Date.now() + AGENT_INFO_MAX_AGE_MS;
|
|
26
|
+
cached = { revision: current, until, info };
|
|
27
|
+
return { ...info, cacheUntil: until };
|
|
28
|
+
},
|
|
29
|
+
invalidate() {
|
|
30
|
+
generation++;
|
|
31
|
+
cached = undefined;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { Helper, Task, Tool, Usage } from "./agent-turn";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Bounds for agent reports shared by the writer and the plugin process adapter.
|
|
5
|
+
* These keep reports, writes and query answers inside the 1 MiB frame limit.
|
|
6
|
+
* Sizes are JSON bytes (UTF-8 after escaping), as they travel.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** The reply's text, the thinking and one helper's answer: 256 KB each. */
|
|
10
|
+
export const TEXT_BYTES = 256 * 1024;
|
|
11
|
+
/** A plan is drawn in every reply of the thread's live query, so it is kept smaller. */
|
|
12
|
+
export const PLAN_BYTES = 64 * 1024;
|
|
13
|
+
/** A step's title or detail, a task, an error: one line of a row. */
|
|
14
|
+
export const LINE_CHARS = 300;
|
|
15
|
+
/** At most this many tasks are kept from a to-do list. */
|
|
16
|
+
export const TASKS_MAX = 100;
|
|
17
|
+
/** One `turns:write` stays under this; what does not fit goes in the next one. */
|
|
18
|
+
export const WRITE_BYTES = 640 * 1024;
|
|
19
|
+
/** Ends a text that reached its limit; nothing is added after it. */
|
|
20
|
+
const CUT = "\n…cut";
|
|
21
|
+
|
|
22
|
+
/** What one character costs inside a JSON string. */
|
|
23
|
+
function cost(point: number): number {
|
|
24
|
+
if (point === 0x22 || point === 0x5c) return 2;
|
|
25
|
+
if (point < 0x20) return [0x08, 0x09, 0x0a, 0x0c, 0x0d].includes(point) ? 2 : 6;
|
|
26
|
+
return point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The size of `value` as JSON, in UTF-8 bytes. */
|
|
30
|
+
export function jsonBytes(value: unknown): number {
|
|
31
|
+
let bytes = 0;
|
|
32
|
+
for (const character of JSON.stringify(value) ?? "null") {
|
|
33
|
+
const point = character.codePointAt(0)!;
|
|
34
|
+
bytes += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
|
|
35
|
+
}
|
|
36
|
+
return bytes;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The longest start of `text` that costs at most `bytes` inside a JSON string (whole characters only). */
|
|
40
|
+
export function fit(text: string, bytes: number): string {
|
|
41
|
+
let used = 0;
|
|
42
|
+
let end = 0;
|
|
43
|
+
for (const character of text) {
|
|
44
|
+
used += cost(character.codePointAt(0)!);
|
|
45
|
+
if (used > bytes) break;
|
|
46
|
+
end += character.length;
|
|
47
|
+
}
|
|
48
|
+
return text.slice(0, end);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* `stored` with `delta` appended, kept under `limit`: a text that would grow
|
|
53
|
+
* past it is cut and ends with `CUT`, and a cut text takes nothing more.
|
|
54
|
+
*/
|
|
55
|
+
export function append(stored: string, delta: string, limit: number): string {
|
|
56
|
+
if (stored.endsWith(CUT)) return stored;
|
|
57
|
+
const room = limit - jsonBytes(stored);
|
|
58
|
+
if (jsonBytes(delta) <= room) return stored + delta;
|
|
59
|
+
return stored + fit(delta, room - jsonBytes(CUT)) + CUT;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One row line: the first line of `text`, at most `LINE_CHARS` characters, "…" when cut. */
|
|
63
|
+
export function line(text: string, chars = LINE_CHARS): string {
|
|
64
|
+
const first = text.split("\n", 1)[0]!;
|
|
65
|
+
return first.length > chars || first !== text ? `${first.slice(0, chars)}…` : first;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const KINDS: readonly string[] = [
|
|
69
|
+
"command",
|
|
70
|
+
"read",
|
|
71
|
+
"edit",
|
|
72
|
+
"search",
|
|
73
|
+
"web",
|
|
74
|
+
"other",
|
|
75
|
+
] satisfies Tool["kind"][];
|
|
76
|
+
const STATES: readonly string[] = ["running", "done", "failed"] satisfies Tool["state"][];
|
|
77
|
+
const TASK_STATES: readonly string[] = ["pending", "running", "done"];
|
|
78
|
+
|
|
79
|
+
/** Refuses a malformed report back to the agent that made it, before anything is stored. */
|
|
80
|
+
export function check(ok: unknown, what: string): asserts ok {
|
|
81
|
+
if (!ok) throw new TypeError(`ai: ${what}`);
|
|
82
|
+
}
|
|
83
|
+
const isText = (value: unknown): value is string => typeof value === "string";
|
|
84
|
+
const isCount = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
85
|
+
|
|
86
|
+
export function checkedText(value: unknown, what: string): string {
|
|
87
|
+
check(isText(value), `${what} takes a string`);
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function checkedTool(tool: Tool): Tool {
|
|
92
|
+
check(isText(tool?.id) && tool.id !== "", "a tool needs an id");
|
|
93
|
+
check(KINDS.includes(tool.kind), `a tool's kind is one of ${KINDS.join(", ")}`);
|
|
94
|
+
check(isText(tool.title), "a tool needs a title");
|
|
95
|
+
check(tool.detail === undefined || isText(tool.detail), "a tool's detail is a string");
|
|
96
|
+
check(STATES.includes(tool.state), `a tool's state is one of ${STATES.join(", ")}`);
|
|
97
|
+
const { id, kind, title, detail, state } = tool;
|
|
98
|
+
return {
|
|
99
|
+
id,
|
|
100
|
+
kind,
|
|
101
|
+
title: line(title),
|
|
102
|
+
...(detail !== undefined && { detail: line(detail) }),
|
|
103
|
+
state,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function checkedHelper(helper: Helper): Helper {
|
|
108
|
+
check(isText(helper?.id) && helper.id !== "", "a helper needs an id");
|
|
109
|
+
check(isText(helper.name) && isText(helper.title), "a helper needs a name and a title");
|
|
110
|
+
check(helper.text === undefined || isText(helper.text), "a helper's text is a string");
|
|
111
|
+
check(STATES.includes(helper.state), `a helper's state is one of ${STATES.join(", ")}`);
|
|
112
|
+
const { id, name, title, state, text } = helper;
|
|
113
|
+
return {
|
|
114
|
+
id,
|
|
115
|
+
name: line(name),
|
|
116
|
+
title: line(title),
|
|
117
|
+
...(text !== undefined && { text: append("", text, TEXT_BYTES) }),
|
|
118
|
+
state,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function checkedTasks(list: readonly Task[]): Task[] {
|
|
123
|
+
check(Array.isArray(list), "tasks(list) takes an array");
|
|
124
|
+
for (const item of list)
|
|
125
|
+
check(isText(item?.text) && TASK_STATES.includes(item.state), "a task is { text, state }");
|
|
126
|
+
return list.slice(0, TASKS_MAX).map(({ text, state }) => ({ text: line(text), state }));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function checkedUsage(usage: Usage): Usage {
|
|
130
|
+
const { inputTokens, outputTokens, cachedInputTokens, costUsd } = usage ?? ({} as Usage);
|
|
131
|
+
check(isCount(inputTokens) && isCount(outputTokens), "usage needs inputTokens and outputTokens (counts)");
|
|
132
|
+
check(cachedInputTokens === undefined || isCount(cachedInputTokens), "cachedInputTokens is a count");
|
|
133
|
+
check(costUsd === undefined || isCount(costUsd), "costUsd is a non-negative number");
|
|
134
|
+
return {
|
|
135
|
+
inputTokens,
|
|
136
|
+
outputTokens,
|
|
137
|
+
...(cachedInputTokens !== undefined && { cachedInputTokens }),
|
|
138
|
+
...(costUsd !== undefined && { costUsd }),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { WORKER_DATA_BYTES } from "./worker-limits";
|
|
2
|
+
import { jsonBytes } from "./agent-reports";
|
|
3
|
+
|
|
4
|
+
/** Full access (never asks) or Ask first: the agent row's Permission level picker. */
|
|
5
|
+
export type Access = "full" | "ask";
|
|
6
|
+
|
|
7
|
+
/** One earlier message of the thread, as a fresh session is given it. */
|
|
8
|
+
export interface HistoryMessage {
|
|
9
|
+
/**
|
|
10
|
+
* "user" for a person, "agent" for any agent's reply (this one or another),
|
|
11
|
+
* "note" for Tokamaq's own line, e.g. that the oldest messages are left out.
|
|
12
|
+
*/
|
|
13
|
+
readonly role: "user" | "agent" | "note";
|
|
14
|
+
/** Who wrote it as the thread shows it: "Sam", "Claude", "Tokamaq". */
|
|
15
|
+
readonly name: string;
|
|
16
|
+
/** Its full text, without command output. */
|
|
17
|
+
readonly text: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A permission question an agent asks on Ask first. The window shows it on the
|
|
22
|
+
* composer as "Claude wants to {action} `{subject}`".
|
|
23
|
+
*/
|
|
24
|
+
export interface Question {
|
|
25
|
+
/**
|
|
26
|
+
* What "Always allow this session" covers: after that answer, a question of
|
|
27
|
+
* the same kind in this thread's session with this agent is approved without
|
|
28
|
+
* asking, until the app quits. The agent picks it ("command:git push", "edit").
|
|
29
|
+
*/
|
|
30
|
+
readonly kind: string;
|
|
31
|
+
/** The verb: "run", "edit", "fetch". */
|
|
32
|
+
readonly action: string;
|
|
33
|
+
/** What it acts on, shown as code: "git push origin feat/csv-export". */
|
|
34
|
+
readonly subject: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The four answers to a question. Each agent plugin translates them for its own program. */
|
|
38
|
+
export type Answer = "approve" | "approveSession" | "decline" | "cancel";
|
|
39
|
+
|
|
40
|
+
/** The turn transport distinguishes Stop from a person answering Cancel on the card. */
|
|
41
|
+
export type TurnAnswer = Answer | "stopping";
|
|
42
|
+
export const ASK_FOR_TURN = Symbol.for("tokamaq.agentTurn.ask");
|
|
43
|
+
|
|
44
|
+
export type TurnRun = Run & {
|
|
45
|
+
[ASK_FOR_TURN](question: Question): Promise<TurnAnswer>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export function askForTurn(run: Run, question: Question): Promise<TurnAnswer> {
|
|
49
|
+
return (run as Partial<TurnRun>)[ASK_FOR_TURN]?.(question) ?? run.ask(question);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function permissionAnswer(answer: TurnAnswer): Answer {
|
|
53
|
+
return answer === "stopping" ? "cancel" : answer;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Where a step or a helper agent is. `ai` closes any still running when the turn ends. */
|
|
57
|
+
export type StepState = "running" | "done" | "failed";
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* One step of the agent's work (a tool call), as a row under the actions line.
|
|
61
|
+
* Report it when it starts and again, with the same `id`, whenever it changes:
|
|
62
|
+
* the latest report wins. `ai` times it; agents send no times. Only the main
|
|
63
|
+
* agent's own steps: steps a helper agent takes inside itself are not
|
|
64
|
+
* reported in milestone 1 (Claude: skip tool uses with a `parent_tool_use_id`).
|
|
65
|
+
*/
|
|
66
|
+
export interface Tool {
|
|
67
|
+
/**
|
|
68
|
+
* The program's own id for the call (Claude's `tool_use` id, a Codex item
|
|
69
|
+
* id). One Codex `fileChange` item touching several files is one step per
|
|
70
|
+
* file, with the id `${itemId}:${path}`.
|
|
71
|
+
*/
|
|
72
|
+
readonly id: string;
|
|
73
|
+
/** Picks the row's icon and the running line's verb ("Running", "Reading", …). */
|
|
74
|
+
readonly kind: "command" | "read" | "edit" | "search" | "web" | "other";
|
|
75
|
+
/** What the row shows: the command line, the path, the pattern, the URL, or the tool's name. */
|
|
76
|
+
readonly title: string;
|
|
77
|
+
/** A short fact on the right ("+6 −2", "4" matches); without it the row shows the step's time. */
|
|
78
|
+
readonly detail?: string;
|
|
79
|
+
readonly state: StepState;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One item of the agent's to-do list, shown as "Tasks". */
|
|
83
|
+
export interface Task {
|
|
84
|
+
readonly text: string;
|
|
85
|
+
readonly state: "pending" | "running" | "done";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* One built-in helper agent the agent started (Claude's Task agents, Codex's
|
|
90
|
+
* sub-agents), drawn as one folded row. Reported like a `Tool`.
|
|
91
|
+
*/
|
|
92
|
+
export interface Helper {
|
|
93
|
+
readonly id: string;
|
|
94
|
+
/** The helper's kind as its program names it ("Explore"). */
|
|
95
|
+
readonly name: string;
|
|
96
|
+
/** What it was asked to do. */
|
|
97
|
+
readonly title: string;
|
|
98
|
+
readonly state: StepState;
|
|
99
|
+
/** Its answer, once it has one; the folded row opens to it. */
|
|
100
|
+
readonly text?: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* What THIS turn has cost so far. A program that counts for the whole thread
|
|
105
|
+
* (Codex's `tokenUsage.total`) reports the difference from before the turn.
|
|
106
|
+
*/
|
|
107
|
+
export interface Usage {
|
|
108
|
+
/** Every input token of the turn, cache reads included. */
|
|
109
|
+
readonly inputTokens: number;
|
|
110
|
+
readonly outputTokens: number;
|
|
111
|
+
/** The part of `inputTokens` read from the program's cache, when it reports it. */
|
|
112
|
+
readonly cachedInputTokens?: number;
|
|
113
|
+
/** In US dollars, when the program reports a price. */
|
|
114
|
+
readonly costUsd?: number;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** An OpenAI-compatible Responses endpoint with a bearer key. */
|
|
118
|
+
export interface LaunchProvider {
|
|
119
|
+
readonly baseUrl: string;
|
|
120
|
+
readonly keyEnv: string;
|
|
121
|
+
readonly key: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface LaunchSettings {
|
|
125
|
+
readonly threadId: string;
|
|
126
|
+
readonly identity: string;
|
|
127
|
+
readonly env: Readonly<Record<string, string>>;
|
|
128
|
+
readonly args: readonly string[];
|
|
129
|
+
readonly provider?: LaunchProvider;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* One turn, handed to the agent's `start` on the sender's own computer. The
|
|
134
|
+
* agent reports into it; `ai` writes every row. A malformed report (an
|
|
135
|
+
* unknown kind or state, an empty id, a negative count) throws from the
|
|
136
|
+
* method, back to the agent.
|
|
137
|
+
*/
|
|
138
|
+
export interface Run {
|
|
139
|
+
/** The thread's folder on this computer; the agent works here, in place. */
|
|
140
|
+
readonly folder: string;
|
|
141
|
+
/** The person's message exactly as stored in the thread. */
|
|
142
|
+
readonly prompt: string;
|
|
143
|
+
readonly model: string;
|
|
144
|
+
/** The level, when the model offers levels. */
|
|
145
|
+
readonly effort?: string;
|
|
146
|
+
/** The speed, when the agent offers speeds. */
|
|
147
|
+
readonly speed?: string;
|
|
148
|
+
/** The mode, when the agent offers modes. */
|
|
149
|
+
readonly mode?: string;
|
|
150
|
+
readonly access: Access;
|
|
151
|
+
/** Caller-only settings fixed for this start. Treat the values as secrets. */
|
|
152
|
+
readonly launchSettings?: LaunchSettings;
|
|
153
|
+
/**
|
|
154
|
+
* The agent's own session to carry on: given when the thread's last turn was
|
|
155
|
+
* this agent's, on this computer. The agent checks it still has it.
|
|
156
|
+
*/
|
|
157
|
+
readonly sessionId?: string;
|
|
158
|
+
/**
|
|
159
|
+
* The full text of every earlier message in the thread, oldest first (the
|
|
160
|
+
* person's and every agent's, without command output). Give it to a fresh
|
|
161
|
+
* session: when there is no `sessionId`, or the session is gone. The thread
|
|
162
|
+
* in the database is the truth, so switching agent in a thread works too.
|
|
163
|
+
* A very long thread gives only its newest messages, with a note when
|
|
164
|
+
* available. QuickJS may trim more history to keep the full prompt.
|
|
165
|
+
*/
|
|
166
|
+
readonly history: readonly HistoryMessage[];
|
|
167
|
+
/** Adds `delta` to the reply's text, which streams into the thread. */
|
|
168
|
+
text(delta: string): void;
|
|
169
|
+
/**
|
|
170
|
+
* Adds `delta` to the turn's thinking, shown folded above the reply, exactly
|
|
171
|
+
* as given: between two separate thinking blocks the agent sends "\n\n".
|
|
172
|
+
*/
|
|
173
|
+
thinking(delta: string): void;
|
|
174
|
+
/** Reports one step; report it again with the same id on every change. */
|
|
175
|
+
tool(tool: Tool): void;
|
|
176
|
+
/** Reports the whole to-do list; each call replaces the last. */
|
|
177
|
+
tasks(tasks: readonly Task[]): void;
|
|
178
|
+
/** Reports a proposed plan as Markdown, shown as a card; each call replaces the last. */
|
|
179
|
+
plan(text: string): void;
|
|
180
|
+
/** Reports one built-in helper agent; report it again with the same id on every change. */
|
|
181
|
+
helper(helper: Helper): void;
|
|
182
|
+
/** Reports the turn's totals so far; each call replaces the last. */
|
|
183
|
+
usage(usage: Usage): void;
|
|
184
|
+
/**
|
|
185
|
+
* Asks the sender before doing something and resolves with their answer.
|
|
186
|
+
* On Full access it resolves "approve" at once and nothing is shown. On
|
|
187
|
+
* Ask first the turn waits, with no time limit, until the sender answers on
|
|
188
|
+
* the card in the window; when the app quits the question expires with it.
|
|
189
|
+
* "cancel" asks the agent to stop the turn. Return `stopped` if it does.
|
|
190
|
+
*/
|
|
191
|
+
ask(question: Question): Promise<Answer>;
|
|
192
|
+
/** Call as soon as a requested session fails or changes, before asking in its replacement. */
|
|
193
|
+
sessionChanged(sessionId: string | undefined): void;
|
|
194
|
+
/** Registers how the agent receives another message during this turn. */
|
|
195
|
+
onSteer(handler: (text: string) => void | Promise<void>): void;
|
|
196
|
+
/** Registers a graceful interrupt; the turn ends once start settles. */
|
|
197
|
+
onStop(handler: () => void | Promise<void>): void;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** How the agent ended and which session the next turn can carry on. */
|
|
201
|
+
export interface TurnResult {
|
|
202
|
+
readonly sessionId: string;
|
|
203
|
+
/** Set only if the agent confirms an interruption; omit if it completes normally. */
|
|
204
|
+
readonly stopped?: true;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Each turn message names the thread and its currently running turn. */
|
|
208
|
+
export interface TurnAddress {
|
|
209
|
+
readonly threadId: string;
|
|
210
|
+
readonly turnId: string;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export type AgentTurnStart = TurnAddress &
|
|
214
|
+
Pick<
|
|
215
|
+
Run,
|
|
216
|
+
| "folder"
|
|
217
|
+
| "prompt"
|
|
218
|
+
| "history"
|
|
219
|
+
| "sessionId"
|
|
220
|
+
| "model"
|
|
221
|
+
| "effort"
|
|
222
|
+
| "speed"
|
|
223
|
+
| "mode"
|
|
224
|
+
| "access"
|
|
225
|
+
| "launchSettings"
|
|
226
|
+
>;
|
|
227
|
+
|
|
228
|
+
/** Bump on incompatible changes to the messages understood by the embedded local host. */
|
|
229
|
+
export const AGENT_TURN_PROTOCOL = 2;
|
|
230
|
+
export const TURN_ENDED = "This turn has ended";
|
|
231
|
+
export type AgentTurnOpen = AgentTurnStart & { version: number };
|
|
232
|
+
|
|
233
|
+
/** The history notice shared by Chat and the local turn transport. */
|
|
234
|
+
export function omittedHistoryNote(count: number): HistoryMessage {
|
|
235
|
+
return {
|
|
236
|
+
role: "note",
|
|
237
|
+
name: "Tokamaq",
|
|
238
|
+
text: `${count} earlier ${count === 1 ? "message" : "messages"} of this thread ${count === 1 ? "is" : "are"} left out.`,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Keep the newest history that fits beside the complete prompt. */
|
|
243
|
+
export function agentTurnHistory(start: AgentTurnStart): Run["history"] | undefined {
|
|
244
|
+
const budget = WORKER_DATA_BYTES - jsonBytes([{ ...start, history: [], version: AGENT_TURN_PROTOCOL }]);
|
|
245
|
+
if (budget < 0) return undefined;
|
|
246
|
+
const { history } = start;
|
|
247
|
+
const omitted = omissionCount(history[0]);
|
|
248
|
+
const oldest = omitted ? 1 : 0;
|
|
249
|
+
let rowsBytes = 0;
|
|
250
|
+
let fitting: { first: number; note: HistoryMessage | undefined } | undefined;
|
|
251
|
+
for (let first = history.length; first >= oldest && rowsBytes <= budget; first--) {
|
|
252
|
+
const count = omitted + first - oldest;
|
|
253
|
+
const note = count ? omittedHistoryNote(count) : undefined;
|
|
254
|
+
const noteBytes = note ? jsonBytes(note) + (first < history.length ? 1 : 0) : 0;
|
|
255
|
+
if (rowsBytes + noteBytes <= budget) fitting = { first, note };
|
|
256
|
+
if (first > oldest) rowsBytes += jsonBytes(history[first - 1]) + (first < history.length ? 1 : 0);
|
|
257
|
+
}
|
|
258
|
+
// A prompt that leaves no space even for a note still starts, without history.
|
|
259
|
+
if (!fitting) return [];
|
|
260
|
+
const rows = history.slice(fitting.first);
|
|
261
|
+
return fitting.note ? [fitting.note, ...rows] : rows;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function omissionCount(leading: HistoryMessage | undefined): number {
|
|
265
|
+
if (leading?.role !== "note" || leading.name !== "Tokamaq") return 0;
|
|
266
|
+
const count = Number(/^([1-9][0-9]*) earlier /.exec(leading.text)?.[1]);
|
|
267
|
+
return Number.isSafeInteger(count) && leading.text === omittedHistoryNote(count).text ? count : 0;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
type ReportMethods = Pick<Run, "text" | "thinking" | "tool" | "tasks" | "plan" | "helper" | "usage">;
|
|
271
|
+
|
|
272
|
+
export type AgentTurnEvent =
|
|
273
|
+
| { [K in keyof ReportMethods]: { kind: K; value: Parameters<ReportMethods[K]>[0] } }[keyof ReportMethods]
|
|
274
|
+
| { kind: "session"; value: string | null }
|
|
275
|
+
| { kind: "steerReady" };
|
|
276
|
+
|
|
277
|
+
export type AgentTurnReport = TurnAddress & { events: AgentTurnEvent[] };
|
|
278
|
+
export type AgentTurnAsk = TurnAddress & { question: Question };
|
|
279
|
+
export type AgentTurnSteer = TurnAddress & { text: string };
|
|
280
|
+
|
|
281
|
+
export * from "./agent-reports";
|
|
282
|
+
export { AGENT_INFO_MAX_AGE_MS, agentInfoCache } from "./agent-info-cache";
|
|
283
|
+
export { agentCommand } from "./agent-command";
|
|
284
|
+
export {
|
|
285
|
+
hasLocalChannel,
|
|
286
|
+
localProviderIdentity,
|
|
287
|
+
localProviders,
|
|
288
|
+
openLocalChannel,
|
|
289
|
+
} from "./internal/contracts";
|