@ai-ecoverse/slicc-agent 7.31.0 → 7.32.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.
- package/README.md +14 -4
- package/dist/agent.js +4 -0
- package/dist/agent.js.map +2 -2
- package/dist/approvals/policy.js +27 -5
- package/dist/approvals/policy.js.map +2 -2
- package/dist/approvals/published.js +18 -0
- package/dist/approvals/published.js.map +7 -0
- package/dist/approvals/record.js +4 -1
- package/dist/approvals/record.js.map +2 -2
- package/dist/approvals/run-licks.js +137 -0
- package/dist/approvals/run-licks.js.map +7 -0
- package/dist/approvals/run-procs.js +127 -0
- package/dist/approvals/run-procs.js.map +7 -0
- package/dist/approvals/run.js +468 -0
- package/dist/approvals/run.js.map +7 -0
- package/dist/approvals/runnable.js +125 -0
- package/dist/approvals/runnable.js.map +7 -0
- package/dist/approvals/sudo.js +29 -1
- package/dist/approvals/sudo.js.map +2 -2
- package/dist/client.js +1 -0
- package/dist/client.js.map +2 -2
- package/dist/control.js +7 -1
- package/dist/control.js.map +2 -2
- package/dist/host.js +69 -16
- package/dist/host.js.map +2 -2
- package/dist/index.js +14 -0
- package/dist/index.js.map +2 -2
- package/dist/licks/extension.js +1 -0
- package/dist/licks/extension.js.map +2 -2
- package/dist/licks/lick.js +1 -0
- package/dist/licks/lick.js.map +2 -2
- package/dist/main.js +1 -0
- package/dist/main.js.map +2 -2
- package/dist/services.js +7 -2
- package/dist/services.js.map +2 -2
- package/dist/spectrum/approvals-port.js +69 -0
- package/dist/spectrum/approvals-port.js.map +2 -2
- package/dist/spectrum/messages.js +2 -1
- package/dist/spectrum/messages.js.map +2 -2
- package/dist/spectrum/monitor-port.js +2 -1
- package/dist/spectrum/monitor-port.js.map +2 -2
- package/dist/types/agent.d.ts +2 -0
- package/dist/types/approvals/policy.d.ts +10 -1
- package/dist/types/approvals/published.d.ts +3 -0
- package/dist/types/approvals/record.d.ts +44 -1
- package/dist/types/approvals/run-licks.d.ts +18 -0
- package/dist/types/approvals/run-procs.d.ts +40 -0
- package/dist/types/approvals/run.d.ts +60 -0
- package/dist/types/approvals/runnable.d.ts +55 -0
- package/dist/types/approvals/sudo.d.ts +3 -1
- package/dist/types/client.d.ts +2 -0
- package/dist/types/host.d.ts +10 -0
- package/dist/types/index.d.ts +4 -1
- package/dist/types/kernel/client.d.ts +35 -0
- package/dist/types/licks/lick.d.ts +1 -1
- package/dist/types/licks/triage.d.ts +1 -1
- package/dist/types/main.d.ts +2 -1
- package/dist/types/services.d.ts +7 -2
- package/dist/types/spectrum/approvals-port.d.ts +10 -2
- package/package.json +3 -3
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/approvals/run.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport {\n type ConversationId,\n defineExtension,\n defineTask,\n type Extension,\n type Harness,\n type NextTaskState,\n type TaskRuntime,\n} from '@earendil-works/pi-durable';\nimport type { AgentsState } from '../agents.ts';\nimport type { SudoRunning } from '../kernel/client.ts';\nimport type { LickEvent, Licks } from '../licks/licks.ts';\nimport {\n type Approval,\n ApprovalsDoc,\n type DecidedBy,\n MAX_DELAY,\n runLive,\n type SudoApproval,\n type SudoRun,\n} from './record.ts';\nimport { endLick, KEEP_HOURS, MIB, startLick } from './run-licks.ts';\nimport {\n aborted,\n adoptable,\n type Exit,\n gone,\n outputOf,\n outputSize,\n type RunKernel,\n removeOutput,\n runTag,\n signalTree,\n sleep,\n tagged,\n type Watcher,\n watchExits,\n} from './run-procs.ts';\nimport { RUN_REASONS, type RunGates, runnable } from './runnable.ts';\n\nexport { clock, duration, endLick, startLick } from './run-licks.ts';\nexport { outputOf, RUN_TAG, RUNS_DIR, type RunKernel, runTag } from './run-procs.ts';\n\nexport const SUDO_RUN_TASK = 'slicc.sudo-run';\nexport const SUDO_RUNS = 'slicc-sudo-runs';\nexport const POLL_MS = 5000;\nexport const KILL_MS = 5000;\nexport const ADOPT_MS = 250;\nexport const ADOPT_TRIES = 5;\nexport const OUTPUT_CAP = 32 * MIB;\nexport const KEEP_MS = KEEP_HOURS * 3_600_000;\n\nexport const RUN_ERRORS = {\n interrupted: 'interrupted before it started',\n reloaded: 'the page reloaded while it ran',\n idle: \"This request isn't running.\",\n gone: 'Its processes are already gone.',\n unseen: \"The kernel's process list isn't available, so it can't be stopped.\",\n} as const;\n\nexport interface SudoRunHost {\n kernel: RunKernel;\n harness: Pick<Harness, 'commit' | 'snapshot'>;\n agents: { state(): Readonly<AgentsState> };\n licks?: Pick<Licks, 'deliver'>;\n boot: string | null;\n server: string;\n conversation: number;\n now?: () => number;\n pollMs?: number;\n killMs?: number;\n adoptMs?: number;\n outputCap?: number;\n keepMs?: number;\n}\n\nexport type RunAnswer = { done: true; error: null } | { done: false; error: string };\n\nexport type Runner = { by: DecidedBy; device?: string };\n\nexport interface SudoRuns {\n readonly extension: Extension;\n bind(host: SudoRunHost): void;\n claim(id: string, runner: Runner, gates: RunGates, context: Context): Promise<RunAnswer>;\n stop(id: string, runner: Runner, context: Context): Promise<RunAnswer>;\n}\n\ntype Input = { approval: string };\ntype Phase =\n | { phase: 'prepare' }\n | { phase: 'call'; server: string; boot: string | null }\n | { phase: 'started'; pid: number; pgid: number; boot: string | null }\n | { phase: 'wait'; pid: number; pgid: number; boot: string | null }\n | { phase: 'ended' }\n | { phase: 'linger' };\ntype Runtime = TaskRuntime<Input, Phase, null, object>;\ntype Next = NextTaskState<Phase, null>;\n\nconst DONE: Next = { status: 'terminal', outcome: { status: 'completed', result: null } };\n\nconst next = (checkpoint: Phase): Next => ({ status: 'running', checkpoint });\n\nconst sudoIn = (items: readonly Approval[] | undefined, id: string) => {\n const item = items?.find((entry) => entry.id === id);\n return item?.kind === 'sudo' ? item : undefined;\n};\n\nasync function itemOf(runtime: Runtime, id: string, context: Context) {\n return sudoIn((await runtime.snapshot(ApprovalsDoc, context))?.items, id);\n}\n\ntype Claimed = SudoApproval & { replay: NonNullable<SudoApproval['replay']>; run: SudoRun };\n\nasync function claimed(runtime: Runtime, id: string, context: Context) {\n const item = await itemOf(runtime, id, context);\n if (item?.replay && item.run?.state === 'starting') return item as Claimed;\n await runtime.commit(async () => DONE, context);\n return undefined;\n}\n\nfunction edit(\n runtime: Runtime,\n id: string,\n change: (run: SudoRun, item: SudoApproval) => void,\n then: Next | undefined,\n context: Context\n): Promise<void> {\n return runtime.commit(async (tx) => {\n const item = sudoIn((await tx.doc(ApprovalsDoc)).items, id);\n if (item?.run) change(item.run, item);\n return then;\n }, context);\n}\n\nconst ended = (run: SudoRun, state: SudoRun['state'], at: number, error?: string) => {\n run.state = state;\n run.endedAt = at;\n if (error) run.error = error;\n};\n\nexport function messageOf(error: unknown): string {\n if ((error as { code?: unknown })?.code === 'ENOSYS') return RUN_REASONS.kernel;\n const text = error instanceof Error ? error.message : String(error);\n return text.trim() || 'the kernel refused to run it';\n}\n\nasync function tell(host: SudoRunHost, made: Promise<LickEvent>) {\n const event = await made.catch(() => undefined);\n if (event) await host.licks?.deliver(event, BACKGROUND_CONTEXT).catch(() => undefined);\n}\n\nconst stopTree = (host: SudoRunHost, id: string) =>\n signalTree(host.kernel, runTag(id), host.killMs ?? KILL_MS);\n\ntype Lookup = () => Promise<SudoRunHost>;\n\nconst nowOf = (host: SudoRunHost) => host.now?.() ?? Date.now();\n\nconst knownBoots = (a: string | null, b: string | null) => a !== null && b !== null;\n\nfunction memory() {\n const calling = new Set<string>();\n const ends = new Map<string, SudoRunning['ended']>();\n const watchers = new Map<string, Promise<Watcher>>();\n return {\n calling,\n ends,\n watcher(host: SudoRunHost, id: string) {\n const found = watchers.get(id) ?? watchExits(host.kernel, runTag(id));\n watchers.set(id, found);\n return found;\n },\n async release(id: string) {\n const found = watchers.get(id);\n watchers.delete(id);\n ends.delete(id);\n calling.delete(id);\n (await found)?.close();\n },\n };\n}\n\ntype Memory = ReturnType<typeof memory>;\n\nfunction starting(lookup: Lookup, mem: Memory) {\n const { calling, ends, watcher, release } = mem;\n const now = nowOf;\n\n async function prepare(id: string, runtime: Runtime, context: Context) {\n const host = await lookup();\n const item = await claimed(runtime, id, context);\n if (!item) return;\n const place = await outputOf(host.kernel, item.replay.user, id, context.abortSignal).catch(\n (error: unknown) => {\n if (context.abortSignal?.aborted) throw error;\n return messageOf(error);\n }\n );\n if (typeof place === 'string')\n return edit(runtime, id, (kept) => ended(kept, 'failed', now(host), place), DONE, context);\n return edit(\n runtime,\n id,\n (kept) => Object.assign(kept, place),\n next({ phase: 'call', server: host.server, boot: host.boot }),\n context\n );\n }\n\n async function adopt(id: string, boot: string | null, runtime: Runtime, context: Context) {\n const host = await lookup();\n const item = await itemOf(runtime, id, context);\n const target = item?.replay?.target ?? 'root';\n let lead = await adoptable(host.kernel, runTag(id), target);\n for (let attempt = 0; !lead && attempt < ADOPT_TRIES - 1; attempt++) {\n await sleep((host.adoptMs ?? ADOPT_MS) * 2 ** attempt, context.abortSignal);\n lead = await adoptable(host.kernel, runTag(id), target);\n }\n if (!lead)\n return edit(\n runtime,\n id,\n (kept) => ended(kept, 'failed', now(host), RUN_ERRORS.interrupted),\n DONE,\n context\n );\n const pgid = lead.pgid ?? lead.pid;\n return edit(\n runtime,\n id,\n (kept) => Object.assign(kept, { state: 'running', pid: lead.pid, pgid }),\n next({ phase: 'started', pid: lead.pid, pgid, boot }),\n context\n );\n }\n\n async function call(\n id: string,\n at: { server: string; boot: string | null },\n runtime: Runtime,\n context: Context\n ) {\n const host = await lookup();\n if (at.server !== host.server || calling.has(id)) return adopt(id, at.boot, runtime, context);\n calling.add(id);\n const item = await claimed(runtime, id, context);\n if (!item) return;\n const { run } = item;\n if (run.stopBy)\n return edit(runtime, id, (kept) => ended(kept, 'stopped', now(host)), DONE, context);\n await watcher(host, id);\n let started: SudoRunning;\n try {\n if (!host.kernel.sudoRun)\n throw Object.assign(new Error(RUN_REASONS.kernel), { code: 'ENOSYS' });\n const asked = host.kernel.sudoRun(item.replay, {\n stdout: run.stdout as string,\n stderr: run.stderr as string,\n tag: runTag(id),\n });\n started = await Promise.race([asked, aborted(context.abortSignal)]);\n } catch (error) {\n await release(id);\n if (context.abortSignal?.aborted) throw error;\n const why = messageOf(error);\n return edit(runtime, id, (kept) => ended(kept, 'failed', now(host), why), DONE, context);\n }\n ends.set(id, started.ended);\n started.ended.catch(() => undefined);\n const { pid, pgid } = started;\n return edit(\n runtime,\n id,\n (kept) => Object.assign(kept, { state: 'running', pid, pgid }),\n next({ phase: 'started', pid, pgid, boot: at.boot }),\n context\n );\n }\n\n async function begun(\n id: string,\n at: { pid: number; pgid: number; boot: string | null },\n runtime: Runtime,\n context: Context\n ) {\n const host = await lookup();\n const item = await itemOf(runtime, id, context);\n if (item?.run) {\n await tell(host, startLick(host, item));\n if (item.run.stopBy) await stopTree(host, id);\n }\n const { pid, pgid, boot } = at;\n await runtime.commit(async () => next({ phase: 'wait', pid, pgid, boot }), context);\n }\n\n return { prepare, call, begun };\n}\n\nfunction watchdog(host: SudoRunHost, id: string, paths: string[], signal: AbortSignal) {\n const cap = host.outputCap ?? OUTPUT_CAP;\n return (async () => {\n for (;;) {\n await sleep(host.pollMs ?? POLL_MS, signal);\n if ((await outputSize(host.kernel, paths)) <= cap) continue;\n await stopTree(host, id);\n return cap;\n }\n })().catch(() => undefined);\n}\n\nfunction finishing(lookup: Lookup, mem: Memory, swept: (host: SudoRunHost) => void) {\n const { ends, watcher, release } = mem;\n const now = nowOf;\n\n async function exitOf(\n host: SudoRunHost,\n id: string,\n pid: number,\n paths: string[],\n context: Context\n ) {\n const seen = await watcher(host, id);\n const end = ends.get(id)?.then(\n (exit) => ({ status: exit.status, ...(exit.signal ? { signal: exit.signal } : {}) }),\n () => new Promise<Exit>(() => undefined)\n );\n const polling = new AbortController();\n const signal = context.abortSignal;\n const quit = () => polling.abort(signal?.reason);\n signal?.addEventListener('abort', quit, { once: true });\n if (signal?.aborted) quit();\n const capped = watchdog(host, id, paths, polling.signal);\n try {\n const exit = await Promise.race([\n seen.waitFor(pid),\n ...(end ? [end] : []),\n gone(host.kernel, pid, host.pollMs ?? POLL_MS, polling.signal),\n ]);\n polling.abort();\n return { exit, cap: await capped };\n } finally {\n signal?.removeEventListener('abort', quit);\n polling.abort();\n }\n }\n\n async function wait(\n id: string,\n at: { pid: number; pgid: number; boot: string | null },\n runtime: Runtime,\n context: Context\n ) {\n const host = await lookup();\n if (knownBoots(at.boot, host.boot) && at.boot !== host.boot) {\n const left = await tagged(host.kernel, runTag(id));\n if (left?.length)\n return runtime.commit(async () => next({ ...at, phase: 'wait', boot: host.boot }), context);\n await release(id);\n return edit(\n runtime,\n id,\n (kept) => ended(kept, 'failed', now(host), RUN_ERRORS.reloaded),\n next({ phase: 'ended' }),\n context\n );\n }\n try {\n const item = await itemOf(runtime, id, context);\n const paths = [item?.run?.stdout, item?.run?.stderr].filter((path): path is string => !!path);\n const { exit, cap } = await exitOf(host, id, at.pid, paths, context);\n const left = ((await tagged(host.kernel, runTag(id))) ?? [])\n .map((row) => row.pid)\n .filter((pid) => pid !== at.pid);\n await edit(\n runtime,\n id,\n (kept) => {\n ended(kept, kept.stopBy || cap ? 'stopped' : 'done', now(host));\n if (exit.status !== undefined) kept.status = exit.status;\n if (exit.signal) kept.signal = exit.signal;\n if (cap) kept.capped = cap;\n if (left.length) kept.survivors = left;\n },\n next({ phase: 'ended' }),\n context\n );\n } finally {\n await release(id);\n }\n }\n\n async function report(id: string, runtime: Runtime, context: Context) {\n const host = await lookup();\n const item = await itemOf(runtime, id, context);\n if (item?.run) await tell(host, endLick(host, item));\n const lingering = !!item?.run?.survivors?.length;\n await runtime.commit(async () => (lingering ? next({ phase: 'linger' }) : DONE), context);\n if (!lingering) swept(host);\n }\n\n async function abort(id: string, runtime: Runtime, context: Context) {\n const host = await lookup();\n const item = await itemOf(runtime, id, context);\n if (item && (runLive(item) || item.run?.survivors?.length)) await stopTree(host, id);\n await release(id);\n await runtime.commit(async (tx) => {\n const kept = sudoIn((await tx.doc(ApprovalsDoc)).items, id);\n if (kept?.run && runLive(kept)) ended(kept.run, 'stopped', now(host));\n return { status: 'terminal', outcome: { status: 'aborted' } };\n }, context);\n const after = await itemOf(runtime, id, context);\n if (after?.run?.pid) await tell(host, endLick(host, after));\n }\n\n return { wait, report, abort };\n}\n\nasync function linger(\n lookup: Lookup,\n swept: (host: SudoRunHost) => void,\n id: string,\n runtime: Runtime,\n context: Context\n) {\n const host = await lookup();\n const item = await itemOf(runtime, id, context);\n let shown = (item?.run?.survivors ?? []).join(',');\n for (;;) {\n await sleep(host.pollMs ?? POLL_MS, context.abortSignal);\n const rows = await tagged(host.kernel, runTag(id));\n if (!rows) continue;\n const pids = rows.map((row) => row.pid);\n if (pids.join(',') === shown) continue;\n shown = pids.join(',');\n const done = !pids.length;\n await edit(\n runtime,\n id,\n (kept) => {\n if (done) delete kept.survivors;\n else kept.survivors = pids;\n },\n done ? DONE : undefined,\n context\n );\n if (!done) continue;\n swept(host);\n return;\n }\n}\n\nfunction sweeper() {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const sweep = async (host: SudoRunHost) => {\n if (timer) clearTimeout(timer);\n timer = undefined;\n const keep = host.keepMs ?? KEEP_MS;\n const at = nowOf(host);\n const items = (await host.harness.snapshot(ApprovalsDoc, BACKGROUND_CONTEXT))?.items ?? [];\n const kept = items.filter(\n (item): item is SudoApproval & { run: SudoRun } =>\n item.kind === 'sudo' &&\n !!item.run?.stdout &&\n !item.run.removed &&\n item.run.endedAt !== undefined &&\n !runLive(item) &&\n !item.run.survivors?.length\n );\n const due = kept.filter((item) => at - (item.run.endedAt as number) >= keep);\n for (const item of due) {\n const paths = [item.run.stdout, item.run.stderr].filter((path): path is string => !!path);\n const user = item.replay?.user;\n if (user) await removeOutput(host.kernel, user, paths);\n }\n if (due.length)\n await host.harness.commit(async (tx) => {\n for (const item of due) {\n const found = sudoIn((await tx.doc(ApprovalsDoc)).items, item.id)?.run;\n if (!found) continue;\n delete found.stdout;\n delete found.stderr;\n found.removed = true;\n }\n }, BACKGROUND_CONTEXT);\n const later = kept\n .filter((item) => !due.includes(item))\n .map((item) => (item.run.endedAt as number) + keep - at);\n if (!later.length) return;\n timer = setTimeout(\n () => void sweep(host).catch(() => undefined),\n Math.min(MAX_DELAY, Math.max(0, Math.min(...later)))\n );\n (timer as { unref?: () => void }).unref?.();\n };\n return (host: SudoRunHost) => void sweep(host).catch(() => undefined);\n}\n\nexport function sudoRuns(): SudoRuns {\n let bind: (host: SudoRunHost) => void = () => undefined;\n let held: SudoRunHost | undefined;\n const bound = new Promise<SudoRunHost>((resolve) => {\n bind = (host) => {\n held = host;\n resolve(host);\n };\n });\n const swept = sweeper();\n const mem = memory();\n const lookup = () => bound;\n const run = {\n ...starting(lookup, mem),\n ...finishing(lookup, mem, swept),\n linger: (id: string, runtime: Runtime, context: Context) =>\n linger(lookup, swept, id, runtime, context),\n };\n const task = defineTask<Input, Phase, null>({\n name: SUDO_RUN_TASK,\n version: 1,\n initial: () => ({ phase: 'prepare' }),\n phases: {\n prepare: (task, runtime, context) => run.prepare(task.input.approval, runtime, context),\n call: (task, runtime, context) =>\n run.call(task.input.approval, task.state.checkpoint, runtime, context),\n started: (task, runtime, context) =>\n run.begun(task.input.approval, task.state.checkpoint, runtime, context),\n wait: (task, runtime, context) =>\n run.wait(task.input.approval, task.state.checkpoint, runtime, context),\n ended: (task, runtime, context) => run.report(task.input.approval, runtime, context),\n linger: (task, runtime, context) => run.linger(task.input.approval, runtime, context),\n },\n abort: (task, runtime, context) => run.abort(task.input.approval, runtime, context),\n });\n return {\n extension: defineExtension({ name: SUDO_RUNS, tasks: [task] }),\n bind: (host) => {\n bind(host);\n swept(host);\n },\n async claim(id, runner, gates, context) {\n const host = held;\n if (!host) return { done: false, error: RUN_REASONS.kernel };\n const at = host.now?.() ?? Date.now();\n return host.harness.commit(async (tx): Promise<RunAnswer> => {\n const item = (await tx.doc(ApprovalsDoc)).items.find((entry) => entry.id === id);\n if (!item) return { done: false, error: `There is no approval ${id}.` };\n const able = runnable(item, at, gates);\n if (able !== true) return { done: false, error: able.reason };\n (item as SudoApproval).run = {\n state: 'starting',\n by: runner.by,\n ...(runner.device ? { device: runner.device } : {}),\n at,\n };\n await tx.createTask(\n task,\n { approval: id },\n {\n ownership: { kind: 'conversation' },\n conversationId: host.conversation as ConversationId,\n background: true,\n }\n );\n return { done: true, error: null };\n }, context);\n },\n async stop(id, runner, context) {\n const host = held;\n if (!host) return { done: false, error: RUN_ERRORS.idle };\n const found = await host.harness.commit(async (tx) => {\n const item = sudoIn((await tx.doc(ApprovalsDoc)).items, id);\n if (!item?.run) return null;\n const live = runLive(item);\n if (live) item.run.stopBy = runner.by;\n return { live, pid: item.run.pid };\n }, context);\n if (!found) return { done: false, error: RUN_ERRORS.idle };\n if (found.live && found.pid === undefined) return { done: true, error: null };\n const sent = await stopTree(host, id);\n if (sent === 'sent') return { done: true, error: null };\n if (sent === 'unknown') return { done: false, error: RUN_ERRORS.unseen };\n return { done: false, error: found.live ? RUN_ERRORS.gone : RUN_ERRORS.idle };\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AACnC;AAAA,EAEE;AAAA,EACA;AAAA,OAKK;AAIP;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,SAAS,YAAY,KAAK,iBAAiB;AACpD;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,aAA4B,gBAAgB;AAErD,SAAS,OAAO,UAAU,WAAAA,UAAS,aAAAC,kBAAiB;AACpD,SAAS,YAAAC,WAAU,SAAS,UAA0B,UAAAC,eAAc;AAE7D,MAAM,gBAAgB;AACtB,MAAM,YAAY;AAClB,MAAM,UAAU;AAChB,MAAM,UAAU;AAChB,MAAM,WAAW;AAC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
7
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { replicatedState } from "@earendil-works/chord";
|
|
2
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
3
|
+
import { live } from "../agents.js";
|
|
4
|
+
import { frozenTarget } from "../freezer/index.js";
|
|
5
|
+
import { MAX_DELAY, REASONS } from "./record.js";
|
|
6
|
+
const SUDO_RUN_PROTOCOL = [1, 16];
|
|
7
|
+
const RUN_REASONS = {
|
|
8
|
+
kind: "Only a sudo request can run now.",
|
|
9
|
+
open: "This request is still open: answer it instead.",
|
|
10
|
+
untimed: "Only a request that timed out can run now.",
|
|
11
|
+
running: "This request is already running.",
|
|
12
|
+
ran: "This request already ran.",
|
|
13
|
+
terminal: "Run it again in the terminal.",
|
|
14
|
+
validate: "sudo -v has no command to run.",
|
|
15
|
+
stdin: "Its input is gone, so it must be asked again.",
|
|
16
|
+
old: "This request is from before Run now, so it must be asked again.",
|
|
17
|
+
off: "Run now is off in the approval policy.",
|
|
18
|
+
gone: "The agent that asked is gone, so it must be asked again.",
|
|
19
|
+
kernel: `Needs slicc-kernel protocol ${SUDO_RUN_PROTOCOL.join(".")} or later.`
|
|
20
|
+
};
|
|
21
|
+
const MINUTE = 6e4;
|
|
22
|
+
function tooOld(minutes) {
|
|
23
|
+
const hours = minutes / 60;
|
|
24
|
+
const span = Number.isInteger(hours) ? `${hours} h` : `${minutes} min`;
|
|
25
|
+
return `It timed out over ${span} ago, so it must be asked again.`;
|
|
26
|
+
}
|
|
27
|
+
const thawFirst = (cone) => `Thaw ${cone} first.`;
|
|
28
|
+
function runnable(item, now, gates) {
|
|
29
|
+
if (item.kind !== "sudo") return { reason: RUN_REASONS.kind };
|
|
30
|
+
if (item.state === "pending") return { reason: RUN_REASONS.open };
|
|
31
|
+
if (item.state !== "unanswered" || item.reason !== REASONS.timeout)
|
|
32
|
+
return { reason: RUN_REASONS.untimed };
|
|
33
|
+
if (item.run)
|
|
34
|
+
return {
|
|
35
|
+
reason: item.run.state === "starting" || item.run.state === "running" ? RUN_REASONS.running : RUN_REASONS.ran
|
|
36
|
+
};
|
|
37
|
+
const agentId = item.requester.agentId;
|
|
38
|
+
if (item.requester.kind !== "agent" || !agentId) return { reason: RUN_REASONS.terminal };
|
|
39
|
+
if (item.detail.validate || item.replay?.validate) return { reason: RUN_REASONS.validate };
|
|
40
|
+
const stdin = item.replay?.stdin ?? item.detail.stdin;
|
|
41
|
+
if (stdin === "pipe" || stdin === "file") return { reason: RUN_REASONS.stdin };
|
|
42
|
+
if (!item.replay?.rootOnly) return { reason: RUN_REASONS.old };
|
|
43
|
+
if (gates.maxAgeMinutes <= 0) return { reason: RUN_REASONS.off };
|
|
44
|
+
const since = item.decidedAt ?? item.expiresAt;
|
|
45
|
+
if (now - since > gates.maxAgeMinutes * MINUTE) return { reason: tooOld(gates.maxAgeMinutes) };
|
|
46
|
+
const frozen = gates.frozen?.(agentId);
|
|
47
|
+
if (frozen) return { reason: thawFirst(frozen) };
|
|
48
|
+
if (gates.gone?.(agentId)) return { reason: RUN_REASONS.gone };
|
|
49
|
+
if (gates.kernel !== true) return { reason: gates.kernel };
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
function runEnds(item, maxAgeMinutes) {
|
|
53
|
+
if (item.kind !== "sudo" || item.state !== "unanswered" || item.run || maxAgeMinutes <= 0)
|
|
54
|
+
return void 0;
|
|
55
|
+
return (item.decidedAt ?? item.expiresAt) + maxAgeMinutes * MINUTE + 1;
|
|
56
|
+
}
|
|
57
|
+
function agentTarget(state, agentId) {
|
|
58
|
+
if (!agentId.startsWith("scoop:")) return `cone:${agentId}`;
|
|
59
|
+
const scoop = state.scoops[agentId];
|
|
60
|
+
return scoop && !live(scoop) && !scoop.frozen ? `cone:${scoop.cone}` : agentId;
|
|
61
|
+
}
|
|
62
|
+
const frozenOf = (state) => (agentId) => frozenTarget(state(), agentTarget(state(), agentId))?.name;
|
|
63
|
+
const goneOf = (state) => (agentId) => {
|
|
64
|
+
const now = state();
|
|
65
|
+
const target = agentTarget(now, agentId);
|
|
66
|
+
return target.startsWith("cone:") ? !now.cones[target.slice(5)] : !now.scoops[agentId];
|
|
67
|
+
};
|
|
68
|
+
function kernelGate(client) {
|
|
69
|
+
if (typeof client?.sudoRun !== "function") return RUN_REASONS.kernel;
|
|
70
|
+
const [major = 0, minor = 0] = client.protocol ?? SUDO_RUN_PROTOCOL;
|
|
71
|
+
const [needMajor, needMinor] = SUDO_RUN_PROTOCOL;
|
|
72
|
+
return major > needMajor || major === needMajor && minor >= needMinor ? true : RUN_REASONS.kernel;
|
|
73
|
+
}
|
|
74
|
+
const listed = (item) => item.kind === "sudo" && item.state === "unanswered" && item.reason === REASONS.timeout;
|
|
75
|
+
function watchRunnable(approvals, changes, gates, clock = {}) {
|
|
76
|
+
const now = clock.now ?? Date.now;
|
|
77
|
+
const setTimer = clock.setTimer ?? ((callback, ms) => {
|
|
78
|
+
const timer = setTimeout(callback, ms);
|
|
79
|
+
return () => clearTimeout(timer);
|
|
80
|
+
});
|
|
81
|
+
const state = replicatedState({});
|
|
82
|
+
let shown = "{}";
|
|
83
|
+
let disarm = () => void 0;
|
|
84
|
+
const refresh = () => {
|
|
85
|
+
disarm();
|
|
86
|
+
const at = now();
|
|
87
|
+
const given = gates();
|
|
88
|
+
const items = (approvals.value ?? []).filter(listed);
|
|
89
|
+
const map = Object.fromEntries(items.map((item) => [item.id, runnable(item, at, given)]));
|
|
90
|
+
const text = JSON.stringify(map);
|
|
91
|
+
if (text !== shown) {
|
|
92
|
+
shown = text;
|
|
93
|
+
state.replace(BACKGROUND_CONTEXT, map);
|
|
94
|
+
}
|
|
95
|
+
const due = items.map((item) => runEnds(item, given.maxAgeMinutes)).filter((end) => end !== void 0 && end > at);
|
|
96
|
+
if (due.length) disarm = setTimer(refresh, Math.min(MAX_DELAY, Math.min(...due) - at));
|
|
97
|
+
};
|
|
98
|
+
const offs = [
|
|
99
|
+
approvals.subscribe(refresh),
|
|
100
|
+
...changes.map((watched) => watched.subscribe(refresh))
|
|
101
|
+
];
|
|
102
|
+
refresh();
|
|
103
|
+
return {
|
|
104
|
+
state,
|
|
105
|
+
refresh,
|
|
106
|
+
dispose() {
|
|
107
|
+
disarm();
|
|
108
|
+
for (const off of offs) off();
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export {
|
|
113
|
+
RUN_REASONS,
|
|
114
|
+
SUDO_RUN_PROTOCOL,
|
|
115
|
+
agentTarget,
|
|
116
|
+
frozenOf,
|
|
117
|
+
goneOf,
|
|
118
|
+
kernelGate,
|
|
119
|
+
runEnds,
|
|
120
|
+
runnable,
|
|
121
|
+
thawFirst,
|
|
122
|
+
tooOld,
|
|
123
|
+
watchRunnable
|
|
124
|
+
};
|
|
125
|
+
//# sourceMappingURL=runnable.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/approvals/runnable.ts"],
|
|
4
|
+
"sourcesContent": ["import { type ReplicatedState, replicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport { type AgentsState, live } from '../agents.ts';\nimport { frozenTarget } from '../freezer/index.ts';\nimport type { LickTarget } from '../licks/lick.ts';\nimport { type Approval, MAX_DELAY, REASONS } from './record.ts';\n\nexport type Runnable = true | { reason: string };\n\nexport type RunGates = {\n maxAgeMinutes: number;\n kernel: true | string;\n frozen?: (agentId: string) => string | undefined;\n gone?: (agentId: string) => boolean;\n};\n\nexport const SUDO_RUN_PROTOCOL: readonly [number, number] = [1, 16];\n\nexport const RUN_REASONS = {\n kind: 'Only a sudo request can run now.',\n open: 'This request is still open: answer it instead.',\n untimed: 'Only a request that timed out can run now.',\n running: 'This request is already running.',\n ran: 'This request already ran.',\n terminal: 'Run it again in the terminal.',\n validate: 'sudo -v has no command to run.',\n stdin: 'Its input is gone, so it must be asked again.',\n old: 'This request is from before Run now, so it must be asked again.',\n off: 'Run now is off in the approval policy.',\n gone: 'The agent that asked is gone, so it must be asked again.',\n kernel: `Needs slicc-kernel protocol ${SUDO_RUN_PROTOCOL.join('.')} or later.`,\n} as const;\n\nconst MINUTE = 60_000;\n\nexport function tooOld(minutes: number): string {\n const hours = minutes / 60;\n const span = Number.isInteger(hours) ? `${hours} h` : `${minutes} min`;\n return `It timed out over ${span} ago, so it must be asked again.`;\n}\n\nexport const thawFirst = (cone: string): string => `Thaw ${cone} first.`;\n\nexport function runnable(item: Approval, now: number, gates: RunGates): Runnable {\n if (item.kind !== 'sudo') return { reason: RUN_REASONS.kind };\n if (item.state === 'pending') return { reason: RUN_REASONS.open };\n if (item.state !== 'unanswered' || item.reason !== REASONS.timeout)\n return { reason: RUN_REASONS.untimed };\n if (item.run)\n return {\n reason:\n item.run.state === 'starting' || item.run.state === 'running'\n ? RUN_REASONS.running\n : RUN_REASONS.ran,\n };\n const agentId = item.requester.agentId;\n if (item.requester.kind !== 'agent' || !agentId) return { reason: RUN_REASONS.terminal };\n if (item.detail.validate || item.replay?.validate) return { reason: RUN_REASONS.validate };\n const stdin = item.replay?.stdin ?? item.detail.stdin;\n if (stdin === 'pipe' || stdin === 'file') return { reason: RUN_REASONS.stdin };\n if (!item.replay?.rootOnly) return { reason: RUN_REASONS.old };\n if (gates.maxAgeMinutes <= 0) return { reason: RUN_REASONS.off };\n const since = item.decidedAt ?? item.expiresAt;\n if (now - since > gates.maxAgeMinutes * MINUTE) return { reason: tooOld(gates.maxAgeMinutes) };\n const frozen = gates.frozen?.(agentId);\n if (frozen) return { reason: thawFirst(frozen) };\n if (gates.gone?.(agentId)) return { reason: RUN_REASONS.gone };\n if (gates.kernel !== true) return { reason: gates.kernel };\n return true;\n}\n\nexport function runEnds(item: Approval, maxAgeMinutes: number): number | undefined {\n if (item.kind !== 'sudo' || item.state !== 'unanswered' || item.run || maxAgeMinutes <= 0)\n return undefined;\n return (item.decidedAt ?? item.expiresAt) + maxAgeMinutes * MINUTE + 1;\n}\n\nexport function agentTarget(state: Readonly<AgentsState>, agentId: string): LickTarget {\n if (!agentId.startsWith('scoop:')) return `cone:${agentId}`;\n const scoop = state.scoops[agentId];\n return scoop && !live(scoop) && !scoop.frozen ? `cone:${scoop.cone}` : (agentId as LickTarget);\n}\n\nexport const frozenOf =\n (state: () => Readonly<AgentsState>) =>\n (agentId: string): string | undefined =>\n frozenTarget(state(), agentTarget(state(), agentId))?.name;\n\nexport const goneOf =\n (state: () => Readonly<AgentsState>) =>\n (agentId: string): boolean => {\n const now = state();\n const target = agentTarget(now, agentId);\n return target.startsWith('cone:') ? !now.cones[target.slice(5)] : !now.scoops[agentId];\n };\n\ntype Protocol = { protocol?: readonly number[]; sudoRun?: unknown };\n\nexport function kernelGate(client: Protocol | undefined): true | string {\n if (typeof client?.sudoRun !== 'function') return RUN_REASONS.kernel;\n const [major = 0, minor = 0] = client.protocol ?? SUDO_RUN_PROTOCOL;\n const [needMajor, needMinor] = SUDO_RUN_PROTOCOL;\n return major > needMajor || (major === needMajor && minor >= needMinor)\n ? true\n : RUN_REASONS.kernel;\n}\n\ntype Watched = { subscribe(listener: () => void): () => void };\n\nexport interface RunnableWatch {\n readonly state: ReplicatedState<Record<string, Runnable>>;\n refresh(): void;\n dispose(): void;\n}\n\nconst listed = (item: Approval) =>\n item.kind === 'sudo' && item.state === 'unanswered' && item.reason === REASONS.timeout;\n\nexport function watchRunnable(\n approvals: Watched & { readonly value: readonly Approval[] | undefined },\n changes: readonly Watched[],\n gates: () => RunGates,\n clock: { now?: () => number; setTimer?: (callback: () => void, ms: number) => () => void } = {}\n): RunnableWatch {\n const now = clock.now ?? Date.now;\n const setTimer =\n clock.setTimer ??\n ((callback: () => void, ms: number) => {\n const timer = setTimeout(callback, ms);\n return () => clearTimeout(timer);\n });\n const state = replicatedState<Record<string, Runnable>>({});\n let shown = '{}';\n let disarm: () => void = () => undefined;\n const refresh = () => {\n disarm();\n const at = now();\n const given = gates();\n const items = (approvals.value ?? []).filter(listed);\n const map = Object.fromEntries(items.map((item) => [item.id, runnable(item, at, given)]));\n const text = JSON.stringify(map);\n if (text !== shown) {\n shown = text;\n state.replace(BACKGROUND_CONTEXT, map);\n }\n const due = items\n .map((item) => runEnds(item, given.maxAgeMinutes))\n .filter((end): end is number => end !== undefined && end > at);\n if (due.length) disarm = setTimer(refresh, Math.min(MAX_DELAY, Math.min(...due) - at));\n };\n const offs = [\n approvals.subscribe(refresh),\n ...changes.map((watched) => watched.subscribe(refresh)),\n ];\n refresh();\n return {\n state,\n refresh,\n dispose() {\n disarm();\n for (const off of offs) off();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAA+B,uBAAuB;AACtD,SAAS,0BAA0B;AACnC,SAA2B,YAAY;AACvC,SAAS,oBAAoB;AAE7B,SAAwB,WAAW,eAAe;AAW3C,MAAM,oBAA+C,CAAC,GAAG,EAAE;AAE3D,MAAM,cAAc;AAAA,EACzB,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,SAAS;AAAA,EACT,KAAK;AAAA,EACL,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,KAAK;AAAA,EACL,KAAK;AAAA,EACL,MAAM;AAAA,EACN,QAAQ,+BAA+B,kBAAkB,KAAK,GAAG,CAAC;AACpE;AAEA,MAAM,SAAS;AAER,SAAS,OAAO,SAAyB;AAC9C,QAAM,QAAQ,UAAU;AACxB,QAAM,OAAO,OAAO,UAAU,KAAK,IAAI,GAAG,KAAK,OAAO,GAAG,OAAO;AAChE,SAAO,qBAAqB,IAAI;AAClC;AAEO,MAAM,YAAY,CAAC,SAAyB,QAAQ,IAAI;AAExD,SAAS,SAAS,MAAgB,KAAa,OAA2B;AAC/E,MAAI,KAAK,SAAS,OAAQ,QAAO,EAAE,QAAQ,YAAY,KAAK;AAC5D,MAAI,KAAK,UAAU,UAAW,QAAO,EAAE,QAAQ,YAAY,KAAK;AAChE,MAAI,KAAK,UAAU,gBAAgB,KAAK,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M;AACnD,UAAM,MAAM,OAAO,YAAY,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,IAAI,SAAS,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC;AACxF,UAAM,OAAO,KAAK,UAAU,GAAG;AAC/B,QAAI,SAAS,OAAO;AAClB,cAAQ;AACR,YAAM,QAAQ,oBAAoB,GAAG;AAAA,IACvC;AACA,UAAM,MAAM,MACT,IAAI,CAAC,SAAS,QAAQ,MAAM,MAAM,aAAa,CAAC,EAChD,OAAO,CAAC,QAAuB,QAAQ,UAAa,MAAM,EAAE;AAC/D,QAAI,IAAI,OAAQ,UAAS,SAAS,SAAS,KAAK,IAAI,WAAW,KAAK,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;AAAA,EACvF;AACA,QAAM,OAAO;AAAA,IACX,UAAU,UAAU,OAAO;AAAA,IAC3B,GAAG,QAAQ,IAAI,CAAC,YAAY,QAAQ,UAAU,OAAO,CAAC;AAAA,EACxD;AACA,UAAQ;AACR,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU;AACR,aAAO;AACP,iBAAW,OAAO,KAAM,KAAI;AAAA,IAC9B;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/approvals/sudo.js
CHANGED
|
@@ -89,6 +89,32 @@ function sudoDetail(request) {
|
|
|
89
89
|
...kernelFacts(request)
|
|
90
90
|
};
|
|
91
91
|
}
|
|
92
|
+
function filesOf(value) {
|
|
93
|
+
if (!Array.isArray(value)) return void 0;
|
|
94
|
+
return value.filter(
|
|
95
|
+
(file) => typeof file === "object" && file !== null && text(file.path) && text(file.sha256)
|
|
96
|
+
).map(({ path, sha256 }) => ({ path, sha256 }));
|
|
97
|
+
}
|
|
98
|
+
function sudoReplay(request) {
|
|
99
|
+
const rootOnly = rootOnlyOf(request.rootOnly);
|
|
100
|
+
const userWritable = filesOf(request.userWritable);
|
|
101
|
+
const tags = Array.isArray(request.tags) ? request.tags.filter(text) : void 0;
|
|
102
|
+
return {
|
|
103
|
+
id: request.id,
|
|
104
|
+
user: request.user,
|
|
105
|
+
...typeof request.uid === "number" ? { uid: request.uid } : {},
|
|
106
|
+
...text(request.target) ? { target: request.target } : {},
|
|
107
|
+
argv: [...request.argv],
|
|
108
|
+
...text(request.path) ? { path: request.path } : {},
|
|
109
|
+
...text(request.cwd) ? { cwd: request.cwd } : {},
|
|
110
|
+
...STDIN.includes(request.stdin) ? { stdin: request.stdin } : {},
|
|
111
|
+
...rootOnly ? { rootOnly } : {},
|
|
112
|
+
...userWritable ? { userWritable } : {},
|
|
113
|
+
...text(request.tag) ? { tag: request.tag } : {},
|
|
114
|
+
...tags ? { tags } : {},
|
|
115
|
+
...validating(request) ? { validate: true } : {}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
92
118
|
function scoopLick(id, agentId, detail, agents) {
|
|
93
119
|
const scoop = agents?.scoops[agentId];
|
|
94
120
|
if (!scoop) return void 0;
|
|
@@ -135,7 +161,8 @@ function createSudo(options) {
|
|
|
135
161
|
tier: "user",
|
|
136
162
|
always: request.always !== false && !validating(request),
|
|
137
163
|
expiresAt: request.expiresAt,
|
|
138
|
-
detail
|
|
164
|
+
detail,
|
|
165
|
+
replay: sudoReplay(request)
|
|
139
166
|
},
|
|
140
167
|
context
|
|
141
168
|
);
|
|
@@ -189,6 +216,7 @@ export {
|
|
|
189
216
|
ownedSudo,
|
|
190
217
|
shellWord,
|
|
191
218
|
sudoDetail,
|
|
219
|
+
sudoReplay,
|
|
192
220
|
sudoRequest,
|
|
193
221
|
sudoRequester,
|
|
194
222
|
timestampFor,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/sudo.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context, ReplicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { AgentsState } from '../agents.ts';\nimport type { AgentCapture } from '../guests/capture.ts';\nimport type { Licks } from '../licks/licks.ts';\nimport { sprinklesOf } from '../sprinkles/cgi.ts';\nimport type { Approvals } from './index.ts';\nimport {\n type Approval,\n type ApprovalRequester,\n cleanReason,\n REASONS,\n type SudoDetail,\n type SudoStdin,\n} from './record.ts';\n\nexport type SudoAnswer = 'once' | 'always' | 'deny';\n\nexport type SudoDenial = { answer: 'deny'; message: string };\n\nexport type SudoTimestamp = { answer: 'once' | 'always'; timestamp: true };\n\nexport type SudoReply = SudoAnswer | SudoDenial | SudoTimestamp;\n\nexport interface SudoRequest {\n id: string;\n kind: 'sudo';\n user: string;\n uid?: number;\n target?: string;\n argv: string[];\n path?: string;\n cwd?: string;\n pid?: number;\n tag?: string;\n tags?: string[];\n tty?: string;\n createdAt?: number;\n expiresAt: number;\n always?: boolean;\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n timestamp?: boolean;\n validate?: boolean;\n}\n\nexport type SudoAsked = { id: string; error: null } | { id: null; error: string };\n\nexport interface AgentSudo extends AgentCapture {\n readonly approvals: ReplicatedState<Approval[]>;\n request(request: SudoRequest, where: string | null, context: Context): Promise<SudoAsked>;\n withdraw(id: string, reason: string | null, context: Context): Promise<void>;\n}\n\nconst SAFE = /^[\\w@%+=:,./-]+$/;\n\nexport const shellWord = (word: string): string =>\n SAFE.test(word) ? word : `'${word.replaceAll(\"'\", `'\\\\''`)}'`;\n\nconst text = (value: unknown): value is string => typeof value === 'string';\n\nexport function sudoRequest(value: unknown): SudoRequest | null {\n const request = value as Partial<SudoRequest> | null;\n if (typeof request !== 'object' || request === null || request.kind !== 'sudo') return null;\n const { argv, user, expiresAt } = request;\n if (!Array.isArray(argv) || !argv.every(text)) return null;\n if (!argv.length && request.validate !== true) return null;\n if (!text(user) || typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return null;\n return request as SudoRequest;\n}\n\nfunction tagOf(tag: unknown): { kind?: unknown; agentId?: unknown; where?: unknown } | null {\n if (!text(tag)) return null;\n try {\n const parsed = JSON.parse(tag);\n return typeof parsed === 'object' && parsed !== null ? parsed : null;\n } catch {\n return null;\n }\n}\n\nconst TERMINAL = 'terminal:';\nconst FOLLOWER = 'follower:';\n\nfunction shownWhere(where: string, given: string | undefined): string {\n if (given) return given;\n if (where.startsWith(TERMINAL)) return 'a terminal';\n if (where.startsWith(FOLLOWER)) return 'a linked device';\n return where;\n}\n\nexport function sudoRequester(\n request: SudoRequest,\n agents: Readonly<AgentsState> | undefined,\n where?: string | null\n): { requester: ApprovalRequester; agentId: string } {\n const tag = tagOf(request.tag);\n const name = request.user;\n const sprinkle = sprinklesOf(Array.isArray(request.tags) ? request.tags.filter(text) : [])[0];\n if (sprinkle)\n return { requester: { kind: 'user', name, where: `the ${sprinkle} sprinkle` }, agentId: '' };\n if (tag?.kind === 'agent' && text(tag.agentId)) {\n const id = tag.agentId.startsWith('cone:') ? tag.agentId.slice('cone:'.length) : tag.agentId;\n const known = agents?.cones[id]?.name ?? agents?.scoops[id]?.name ?? name;\n return { requester: { kind: 'agent', name: known, agentId: id }, agentId: id };\n }\n if (tag?.kind === 'user' && text(tag.where)) {\n const given = cleanReason(where);\n const device = tag.where.startsWith(FOLLOWER) ? tag.where.slice(FOLLOWER.length) : '';\n return {\n requester: {\n kind: 'user',\n name,\n where: shownWhere(tag.where, given),\n ...(device ? { device } : {}),\n },\n agentId: '',\n };\n }\n return { requester: { kind: 'user', name }, agentId: '' };\n}\n\nconst STDIN: readonly unknown[] = ['tty', 'none', 'pipe', 'file'];\n\nfunction rootOnlyOf(value: unknown): Record<string, boolean> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const kept = Object.entries(value).filter(\n (entry): entry is [string, boolean] => typeof entry[1] === 'boolean'\n );\n return Object.fromEntries(kept);\n}\n\nfunction kernelFacts(request: SudoRequest): Partial<SudoDetail> {\n const rootOnly = rootOnlyOf(request.rootOnly);\n return {\n ...(STDIN.includes(request.stdin) ? { stdin: request.stdin } : {}),\n ...(rootOnly ? { rootOnly } : {}),\n ...(typeof request.always === 'boolean' ? { writable: request.always } : {}),\n };\n}\n\nexport const validating = (request: Pick<SudoRequest, 'validate'>): boolean =>\n request.validate === true;\n\nexport const timestampFor = (user: string): string =>\n `start a sudo timestamp for ${user} (no command)`;\n\nexport function sudoDetail(request: SudoRequest): SudoDetail {\n if (validating(request))\n return { command: timestampFor(request.user), validate: true, writable: false };\n const command = [request.path || request.argv[0], ...request.argv.slice(1)]\n .map((word) => shellWord(String(word)))\n .join(' ');\n return {\n command,\n ...(text(request.target) ? { target: request.target } : {}),\n ...(text(request.cwd) ? { cwd: request.cwd } : {}),\n ...(request.always === true ? { alwaysScope: 'cwd' as const } : {}),\n ...kernelFacts(request),\n };\n}\n\nfunction scoopLick(\n id: string,\n agentId: string,\n detail: SudoDetail,\n agents: Readonly<AgentsState> | undefined\n) {\n const scoop = agents?.scoops[agentId];\n if (!scoop) return undefined;\n const { command, target, cwd, validate } = detail;\n const as = target ? ` as ${target}` : '';\n const at = cwd ? ` in ${cwd}` : '';\n const asked = validate ? 'to start a sudo timestamp' : `to run ${command}${as}${at}`;\n return {\n channel: 'sudo-request' as const,\n source: id,\n title: `${scoop.name} waits for sudo`,\n text: `[scoop ${scoop.name} waits for a person to approve sudo]`,\n body: `${scoop.name} asked ${asked}. A person answers it in the approvals dialog; you can't approve it. It ends when someone answers or it times out.`,\n target: `cone:${scoop.cone}` as const,\n };\n}\n\nexport interface SudoAttach {\n approvals: Approvals;\n capture: AgentCapture;\n agents?: () => Readonly<AgentsState> | undefined;\n licks?: Pick<Licks, 'deliver'>;\n}\n\ntype SudoLick = NonNullable<ReturnType<typeof scoopLick>>;\n\nexport function createSudo(options: SudoAttach): AgentSudo & { close(): void } {\n const { approvals } = options;\n const agents = () => options.agents?.();\n const waiting = new Map<string, SudoLick>();\n const send = (lick: SudoLick) =>\n void options.licks?.deliver(lick, BACKGROUND_CONTEXT).catch(() => undefined);\n const watch = (items: readonly Approval[]) => {\n for (const [id, lick] of waiting) {\n const item = items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.tier !== 'user') continue;\n waiting.delete(id);\n if (item?.state === 'pending') send(lick);\n }\n };\n const off = approvals.state.subscribe((items) => watch(items));\n return {\n approvals: approvals.state,\n capture: (request, where, context) => options.capture.capture(request, where, context),\n async request(value, where, context) {\n const request = sudoRequest(value);\n if (!request) return { id: null, error: 'This is not a sudo request.' };\n const { requester, agentId } = sudoRequester(request, agents(), where);\n const detail = sudoDetail(request);\n const item = await approvals.request(\n {\n kind: 'sudo',\n agentId,\n requester,\n tier: 'user',\n always: request.always !== false && !validating(request),\n expiresAt: request.expiresAt,\n detail,\n },\n context\n );\n const lick = scoopLick(item.id, agentId, detail, agents());\n if (lick) {\n waiting.set(item.id, lick);\n watch(approvals.state.value as Approval[]);\n }\n return { id: item.id, error: null };\n },\n async withdraw(id, reason, context) {\n await approvals.withdraw(id, reason, context);\n },\n close() {\n off();\n waiting.clear();\n },\n };\n}\n\nexport function ownedSudo(sudo: AgentSudo): AgentSudo & { release(): void } {\n const mine = new Set<string>();\n const forget = () => {\n const open = new Set(\n (sudo.approvals.value as Approval[])\n .filter((item) => item.state === 'pending')\n .map(({ id }) => id)\n );\n for (const id of mine) if (!open.has(id)) mine.delete(id);\n };\n return {\n approvals: sudo.approvals,\n capture: (request, where, context) => sudo.capture(request, where, context),\n async request(request, where, context) {\n forget();\n const asked = await sudo.request(request, where, context);\n if (asked.id) mine.add(asked.id);\n return asked;\n },\n async withdraw(id, reason, context) {\n if (!mine.delete(id)) return;\n await sudo.withdraw(id, reason, context);\n },\n release() {\n forget();\n for (const id of mine)\n void sudo.withdraw(id, REASONS.disconnected, BACKGROUND_CONTEXT).catch(() => undefined);\n mine.clear();\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,0BAA0B;AAInC,SAAS,mBAAmB;AAE5B;AAAA,EAGE;AAAA,EACA;AAAA,
|
|
4
|
+
"sourcesContent": ["import type { Context, ReplicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { AgentsState } from '../agents.ts';\nimport type { AgentCapture } from '../guests/capture.ts';\nimport type { Licks } from '../licks/licks.ts';\nimport { sprinklesOf } from '../sprinkles/cgi.ts';\nimport type { Approvals } from './index.ts';\nimport {\n type Approval,\n type ApprovalRequester,\n cleanReason,\n REASONS,\n type SudoDetail,\n type SudoFile,\n type SudoReplay,\n type SudoStdin,\n} from './record.ts';\n\nexport type SudoAnswer = 'once' | 'always' | 'deny';\n\nexport type SudoDenial = { answer: 'deny'; message: string };\n\nexport type SudoTimestamp = { answer: 'once' | 'always'; timestamp: true };\n\nexport type SudoReply = SudoAnswer | SudoDenial | SudoTimestamp;\n\nexport interface SudoRequest {\n id: string;\n kind: 'sudo';\n user: string;\n uid?: number;\n target?: string;\n argv: string[];\n path?: string;\n cwd?: string;\n pid?: number;\n tag?: string;\n tags?: string[];\n tty?: string;\n createdAt?: number;\n expiresAt: number;\n always?: boolean;\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n userWritable?: SudoFile[];\n timestamp?: boolean;\n validate?: boolean;\n}\n\nexport type SudoAsked = { id: string; error: null } | { id: null; error: string };\n\nexport interface AgentSudo extends AgentCapture {\n readonly approvals: ReplicatedState<Approval[]>;\n request(request: SudoRequest, where: string | null, context: Context): Promise<SudoAsked>;\n withdraw(id: string, reason: string | null, context: Context): Promise<void>;\n}\n\nconst SAFE = /^[\\w@%+=:,./-]+$/;\n\nexport const shellWord = (word: string): string =>\n SAFE.test(word) ? word : `'${word.replaceAll(\"'\", `'\\\\''`)}'`;\n\nconst text = (value: unknown): value is string => typeof value === 'string';\n\nexport function sudoRequest(value: unknown): SudoRequest | null {\n const request = value as Partial<SudoRequest> | null;\n if (typeof request !== 'object' || request === null || request.kind !== 'sudo') return null;\n const { argv, user, expiresAt } = request;\n if (!Array.isArray(argv) || !argv.every(text)) return null;\n if (!argv.length && request.validate !== true) return null;\n if (!text(user) || typeof expiresAt !== 'number' || !Number.isFinite(expiresAt)) return null;\n return request as SudoRequest;\n}\n\nfunction tagOf(tag: unknown): { kind?: unknown; agentId?: unknown; where?: unknown } | null {\n if (!text(tag)) return null;\n try {\n const parsed = JSON.parse(tag);\n return typeof parsed === 'object' && parsed !== null ? parsed : null;\n } catch {\n return null;\n }\n}\n\nconst TERMINAL = 'terminal:';\nconst FOLLOWER = 'follower:';\n\nfunction shownWhere(where: string, given: string | undefined): string {\n if (given) return given;\n if (where.startsWith(TERMINAL)) return 'a terminal';\n if (where.startsWith(FOLLOWER)) return 'a linked device';\n return where;\n}\n\nexport function sudoRequester(\n request: SudoRequest,\n agents: Readonly<AgentsState> | undefined,\n where?: string | null\n): { requester: ApprovalRequester; agentId: string } {\n const tag = tagOf(request.tag);\n const name = request.user;\n const sprinkle = sprinklesOf(Array.isArray(request.tags) ? request.tags.filter(text) : [])[0];\n if (sprinkle)\n return { requester: { kind: 'user', name, where: `the ${sprinkle} sprinkle` }, agentId: '' };\n if (tag?.kind === 'agent' && text(tag.agentId)) {\n const id = tag.agentId.startsWith('cone:') ? tag.agentId.slice('cone:'.length) : tag.agentId;\n const known = agents?.cones[id]?.name ?? agents?.scoops[id]?.name ?? name;\n return { requester: { kind: 'agent', name: known, agentId: id }, agentId: id };\n }\n if (tag?.kind === 'user' && text(tag.where)) {\n const given = cleanReason(where);\n const device = tag.where.startsWith(FOLLOWER) ? tag.where.slice(FOLLOWER.length) : '';\n return {\n requester: {\n kind: 'user',\n name,\n where: shownWhere(tag.where, given),\n ...(device ? { device } : {}),\n },\n agentId: '',\n };\n }\n return { requester: { kind: 'user', name }, agentId: '' };\n}\n\nconst STDIN: readonly unknown[] = ['tty', 'none', 'pipe', 'file'];\n\nfunction rootOnlyOf(value: unknown): Record<string, boolean> | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const kept = Object.entries(value).filter(\n (entry): entry is [string, boolean] => typeof entry[1] === 'boolean'\n );\n return Object.fromEntries(kept);\n}\n\nfunction kernelFacts(request: SudoRequest): Partial<SudoDetail> {\n const rootOnly = rootOnlyOf(request.rootOnly);\n return {\n ...(STDIN.includes(request.stdin) ? { stdin: request.stdin } : {}),\n ...(rootOnly ? { rootOnly } : {}),\n ...(typeof request.always === 'boolean' ? { writable: request.always } : {}),\n };\n}\n\nexport const validating = (request: Pick<SudoRequest, 'validate'>): boolean =>\n request.validate === true;\n\nexport const timestampFor = (user: string): string =>\n `start a sudo timestamp for ${user} (no command)`;\n\nexport function sudoDetail(request: SudoRequest): SudoDetail {\n if (validating(request))\n return { command: timestampFor(request.user), validate: true, writable: false };\n const command = [request.path || request.argv[0], ...request.argv.slice(1)]\n .map((word) => shellWord(String(word)))\n .join(' ');\n return {\n command,\n ...(text(request.target) ? { target: request.target } : {}),\n ...(text(request.cwd) ? { cwd: request.cwd } : {}),\n ...(request.always === true ? { alwaysScope: 'cwd' as const } : {}),\n ...kernelFacts(request),\n };\n}\n\nfunction filesOf(value: unknown): SudoFile[] | undefined {\n if (!Array.isArray(value)) return undefined;\n return value\n .filter(\n (file): file is SudoFile =>\n typeof file === 'object' && file !== null && text(file.path) && text(file.sha256)\n )\n .map(({ path, sha256 }) => ({ path, sha256 }));\n}\n\nexport function sudoReplay(request: SudoRequest): SudoReplay {\n const rootOnly = rootOnlyOf(request.rootOnly);\n const userWritable = filesOf(request.userWritable);\n const tags = Array.isArray(request.tags) ? request.tags.filter(text) : undefined;\n return {\n id: request.id,\n user: request.user,\n ...(typeof request.uid === 'number' ? { uid: request.uid } : {}),\n ...(text(request.target) ? { target: request.target } : {}),\n argv: [...request.argv],\n ...(text(request.path) ? { path: request.path } : {}),\n ...(text(request.cwd) ? { cwd: request.cwd } : {}),\n ...(STDIN.includes(request.stdin) ? { stdin: request.stdin } : {}),\n ...(rootOnly ? { rootOnly } : {}),\n ...(userWritable ? { userWritable } : {}),\n ...(text(request.tag) ? { tag: request.tag } : {}),\n ...(tags ? { tags } : {}),\n ...(validating(request) ? { validate: true } : {}),\n };\n}\n\nfunction scoopLick(\n id: string,\n agentId: string,\n detail: SudoDetail,\n agents: Readonly<AgentsState> | undefined\n) {\n const scoop = agents?.scoops[agentId];\n if (!scoop) return undefined;\n const { command, target, cwd, validate } = detail;\n const as = target ? ` as ${target}` : '';\n const at = cwd ? ` in ${cwd}` : '';\n const asked = validate ? 'to start a sudo timestamp' : `to run ${command}${as}${at}`;\n return {\n channel: 'sudo-request' as const,\n source: id,\n title: `${scoop.name} waits for sudo`,\n text: `[scoop ${scoop.name} waits for a person to approve sudo]`,\n body: `${scoop.name} asked ${asked}. A person answers it in the approvals dialog; you can't approve it. It ends when someone answers or it times out.`,\n target: `cone:${scoop.cone}` as const,\n };\n}\n\nexport interface SudoAttach {\n approvals: Approvals;\n capture: AgentCapture;\n agents?: () => Readonly<AgentsState> | undefined;\n licks?: Pick<Licks, 'deliver'>;\n}\n\ntype SudoLick = NonNullable<ReturnType<typeof scoopLick>>;\n\nexport function createSudo(options: SudoAttach): AgentSudo & { close(): void } {\n const { approvals } = options;\n const agents = () => options.agents?.();\n const waiting = new Map<string, SudoLick>();\n const send = (lick: SudoLick) =>\n void options.licks?.deliver(lick, BACKGROUND_CONTEXT).catch(() => undefined);\n const watch = (items: readonly Approval[]) => {\n for (const [id, lick] of waiting) {\n const item = items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.tier !== 'user') continue;\n waiting.delete(id);\n if (item?.state === 'pending') send(lick);\n }\n };\n const off = approvals.state.subscribe((items) => watch(items));\n return {\n approvals: approvals.state,\n capture: (request, where, context) => options.capture.capture(request, where, context),\n async request(value, where, context) {\n const request = sudoRequest(value);\n if (!request) return { id: null, error: 'This is not a sudo request.' };\n const { requester, agentId } = sudoRequester(request, agents(), where);\n const detail = sudoDetail(request);\n const item = await approvals.request(\n {\n kind: 'sudo',\n agentId,\n requester,\n tier: 'user',\n always: request.always !== false && !validating(request),\n expiresAt: request.expiresAt,\n detail,\n replay: sudoReplay(request),\n },\n context\n );\n const lick = scoopLick(item.id, agentId, detail, agents());\n if (lick) {\n waiting.set(item.id, lick);\n watch(approvals.state.value as Approval[]);\n }\n return { id: item.id, error: null };\n },\n async withdraw(id, reason, context) {\n await approvals.withdraw(id, reason, context);\n },\n close() {\n off();\n waiting.clear();\n },\n };\n}\n\nexport function ownedSudo(sudo: AgentSudo): AgentSudo & { release(): void } {\n const mine = new Set<string>();\n const forget = () => {\n const open = new Set(\n (sudo.approvals.value as Approval[])\n .filter((item) => item.state === 'pending')\n .map(({ id }) => id)\n );\n for (const id of mine) if (!open.has(id)) mine.delete(id);\n };\n return {\n approvals: sudo.approvals,\n capture: (request, where, context) => sudo.capture(request, where, context),\n async request(request, where, context) {\n forget();\n const asked = await sudo.request(request, where, context);\n if (asked.id) mine.add(asked.id);\n return asked;\n },\n async withdraw(id, reason, context) {\n if (!mine.delete(id)) return;\n await sudo.withdraw(id, reason, context);\n },\n release() {\n forget();\n for (const id of mine)\n void sudo.withdraw(id, REASONS.disconnected, BACKGROUND_CONTEXT).catch(() => undefined);\n mine.clear();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AAInC,SAAS,mBAAmB;AAE5B;AAAA,EAGE;AAAA,EACA;AAAA,OAKK;AAyCP,MAAM,OAAO;AAEN,MAAM,YAAY,CAAC,SACxB,KAAK,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,KAAK,OAAO,CAAC;AAE5D,MAAM,OAAO,CAAC,UAAoC,OAAO,UAAU;AAE5D,SAAS,YAAY,OAAoC;AAC9D,QAAM,UAAU;AAChB,MAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,QAAQ,SAAS,OAAQ,QAAO;AACvF,QAAM,EAAE,MAAM,MAAM,UAAU,IAAI;AAClC,MAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,CAAC,KAAK,MAAM,IAAI,EAAG,QAAO;AACtD,MAAI,CAAC,KAAK,UAAU,QAAQ,aAAa,KAAM,QAAO;AACtD,MAAI,CAAC,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,OAAO;AAAA,IAC9C;AAAA,IACA,QAAQ;AACN,UAAI;AACJ,cAAQ,MAAM;AAAA,IAChB;AAAA,EACF;AACF;AAEO,SAAS,UAAU,MAAkD;AAC1E,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,SAAS,MAAM;AACnB,UAAM,OAAO,IAAI;AAAA,MACd,KAAK,UAAU,MACb,OAAO,CAAC,SAAS,KAAK,UAAU,SAAS,EACzC,IAAI,CAAC,EAAE,GAAG,MAAM,EAAE;AAAA,IACvB;AACA,eAAW,MAAM,KAAM,KAAI,CAAC,KAAK,IAAI,EAAE,EAAG,MAAK,OAAO,EAAE;AAAA,EAC1D;AACA,SAAO;AAAA,IACL,WAAW,KAAK;AAAA,IAChB,SAAS,CAAC,SAAS,OAAO,YAAY,KAAK,QAAQ,SAAS,OAAO,OAAO;AAAA,IAC1E,MAAM,QAAQ,SAAS,OAAO,SAAS;AACrC,aAAO;AACP,YAAM,QAAQ,MAAM,KAAK,QAAQ,SAAS,OAAO,OAAO;AACxD,UAAI,MAAM,GAAI,MAAK,IAAI,MAAM,EAAE;AAC/B,aAAO;AAAA,IACT;AAAA,IACA,MAAM,SAAS,IAAI,QAAQ,SAAS;AAClC,UAAI,CAAC,KAAK,OAAO,EAAE,EAAG;AACtB,YAAM,KAAK,SAAS,IAAI,QAAQ,OAAO;AAAA,IACzC;AAAA,IACA,UAAU;AACR,aAAO;AACP,iBAAW,MAAM;AACf,aAAK,KAAK,SAAS,IAAI,QAAQ,cAAc,kBAAkB,EAAE,MAAM,MAAM,MAAS;AACxF,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/client.js
CHANGED
|
@@ -186,6 +186,7 @@ async function connectAgent(endpoint, options = {}) {
|
|
|
186
186
|
owner: pagesHandle.variant === "pages",
|
|
187
187
|
approvals: hold(state("approvals")),
|
|
188
188
|
approvalPolicy: hold(state("approvalPolicy")),
|
|
189
|
+
approvalRunnable: hold(state("approvalRunnable")),
|
|
189
190
|
settings: lastingSettings(settings, hold),
|
|
190
191
|
remote,
|
|
191
192
|
history: offers(controlHandle, "entries"),
|
package/dist/client.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type Context,\n createHost,\n type Host,\n isChordError,\n type Readable,\n type ReplicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { ApprovalPolicy } from './approvals/policy.ts';\nimport type { Approval } from './approvals/record.ts';\nimport type { ChangesView } from './changes/git.ts';\nimport type { FrozenCone } from './freezer/index.ts';\nimport type { ImportProgress } from './freezer/v6.ts';\nimport type { GuestSeat } from './guests/seats.ts';\nimport type { MemoryEntry, MemoryScope } from './memory/format.ts';\nimport { controlAnswer, pageAnswer, remoteAnswer, settingsAnswer } from './readonly.ts';\nimport type { AgentRemote } from './remote/host.ts';\nimport type { AgentPages } from './remote/pages.ts';\nimport type { VaultState } from './secrets/vault.ts';\nimport {\n AgentControl,\n AgentInventoryService,\n AgentPagesService,\n AgentRemoteService,\n AgentSettings,\n type AgentsSummary,\n AgentTranscript,\n CONTROL_METHODS,\n type Command,\n type Delivered,\n type GuestProposal,\n type GuestShown,\n type InventoryState,\n type MonitorFeed,\n OWNER_SETTINGS_METHODS,\n PAGE_METHODS,\n type PrivateRevision,\n REMOTE_METHODS,\n type SendMode,\n type SettingsState,\n TRANSCRIPT_STATES,\n} from './services.ts';\nimport {\n type AgentPrincipal,\n bound,\n offers,\n type Remote,\n type Root,\n replicated,\n SELF,\n} from './serving.ts';\nimport type { Sprinkle } from './sprinkles/kind.ts';\nimport { otherVersion, type PortEndpoint, PortLink } from './wire.ts';\n\nexport interface AgentConnection {\n readonly serverId: string;\n readonly control: AgentControl;\n readonly transcript: ReplicatedState<ConversationView>;\n readonly deliveries: ReplicatedState<Record<string, Delivered>>;\n readonly agents?: ReplicatedState<AgentsSummary>;\n readonly views?: ReplicatedState<Record<string, ConversationView>>;\n readonly commands?: ReplicatedState<Command[]>;\n readonly privateRevision?: ReplicatedState<PrivateRevision>;\n readonly sprinkles?: ReplicatedState<Sprinkle[]>;\n readonly memories?: ReplicatedState<MemoryEntry[]>;\n readonly memoryScopes?: ReplicatedState<MemoryScope[]>;\n readonly frozen?: ReplicatedState<FrozenCone[]>;\n readonly importing?: ReplicatedState<ImportProgress>;\n readonly changes?: ReplicatedState<ChangesView>;\n readonly monitor?: ReplicatedState<MonitorFeed>;\n readonly vault?: ReplicatedState<VaultState>;\n readonly labels?: ReplicatedState<Record<string, string>>;\n readonly guests?: ReplicatedState<GuestSeat[]>;\n readonly viewOnly?: boolean;\n readonly guest?: GuestShown;\n readonly proposals?: ReplicatedState<GuestProposal[]>;\n readonly owner?: boolean;\n readonly approvals?: ReplicatedState<Approval[]>;\n readonly approvalPolicy?: ReplicatedState<ApprovalPolicy>;\n readonly settings: AgentSettings;\n readonly remote?: AgentRemote;\n readonly history?: boolean;\n readonly pages?: AgentPages;\n readonly inventory?: ReplicatedState<InventoryState>;\n readonly closed: Promise<Error | undefined>;\n readonly readOnly?: boolean;\n prompt(text: string, whenBusy?: SendMode): Promise<string>;\n webhook(\n name: string,\n delivery: { id?: string | null; headers?: Record<string, string>; body: string }\n ): Promise<{ delivered: boolean }>;\n close(): Promise<void>;\n}\n\nexport interface Lasting<T> {\n readonly state: ReplicatedState<T>;\n freeze(): void;\n}\n\nexport function lasting<T>(state: ReplicatedState<T>): Lasting<T> {\n let last: T | undefined;\n let frozen = false;\n const read = () => {\n if (frozen) return last;\n try {\n last = state.value;\n } catch {}\n return last;\n };\n return {\n state: {\n get value() {\n return read();\n },\n subscribe: (listener) => (frozen ? () => undefined : state.subscribe(listener)),\n },\n freeze() {\n read();\n frozen = true;\n },\n };\n}\n\nexport function lastingSettings(\n settings: AgentSettings,\n hold: <T>(state: ReplicatedState<T>) => ReplicatedState<T>\n): AgentSettings {\n return {\n state: hold(settings.state),\n connect: (providerId, secret, fields, context) =>\n settings.connect(providerId, secret, fields, context),\n disconnect: (providerId, context) => settings.disconnect(providerId, context),\n remove: (providerId, context) => settings.remove(providerId, context),\n serverUrl: (providerId, context) => settings.serverUrl(providerId, context),\n signIn: (providerId, context) => settings.signIn(providerId, context),\n dismissMoved: (context) => settings.dismissMoved(context),\n addServer: (name, entry, context) => settings.addServer(name, entry, context),\n removeServer: (id, context) => settings.removeServer(id, context),\n refusals: (context) => settings.refusals(context),\n };\n}\n\nconst VERSIONS = new Set(['upgrade_required', 'contract_mismatch']);\n\nexport const final = (error: unknown): unknown =>\n isChordError(error) && VERSIONS.has(error.code) ? otherVersion(error) : error;\n\nexport const ended = (link: PortLink): Promise<never> =>\n link.ended.then((reason) => {\n throw reason ?? new Error('the agent closed the link');\n });\n\ntype Contract = Parameters<Host<AgentPrincipal>['get']>[0];\n\nexport function clientHost(link: PortLink, name: string): Host<AgentPrincipal> {\n const host = createHost<AgentPrincipal>({\n name: `${name}:${crypto.randomUUID()}`,\n kind: 'client',\n self: SELF,\n });\n host.connect(link, { principal: SELF, onProtocolMismatch: () => link.mismatched() });\n return host;\n}\n\nexport async function holding(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contracts: readonly Contract[]\n): Promise<Remote[]> {\n const stop = new AbortController();\n const getting = contracts.map(\n (contract) =>\n host.get(contract, {}, { signal: stop.signal }) as Promise<unknown> as Promise<Remote>\n );\n try {\n return await Promise.race([Promise.all(getting), ended(link)]);\n } catch (error) {\n stop.abort();\n for (const got of getting)\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n link.close('handshake failed');\n void host.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function optional(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contract: Contract\n): Promise<Remote | undefined> {\n const got = host.get(contract, {}) as Promise<unknown> as Promise<Remote>;\n return Promise.race([got, ended(link)]).catch(() => {\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n return undefined;\n });\n}\n\nexport async function connectAgent(\n endpoint: PortEndpoint,\n options: { context?: Context } = {}\n): Promise<AgentConnection> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const link = new PortLink(endpoint);\n const serverId = await link.hello;\n const host = clientHost(link, 'follower');\n const inventory = optional(host, link, AgentInventoryService);\n const handles = await holding(host, link, [\n AgentControl,\n AgentTranscript,\n AgentSettings,\n AgentRemoteService,\n AgentPagesService,\n ]).catch((error: unknown) => {\n void inventory.then((handle) => handle?.release());\n throw final(error);\n });\n const [controlHandle, transcriptHandle, settingsHandle, remoteHandle, pagesHandle] = handles as [\n Remote,\n Remote,\n Remote,\n Remote,\n Remote,\n ];\n const inventoryHandle = await inventory;\n const release = () => {\n for (const handle of handles) handle.release();\n inventoryHandle?.release();\n };\n const root: Root = (run, rootOptions) => host.root(run, rootOptions);\n const control = bound<AgentControl>(controlHandle, root, CONTROL_METHODS, controlAnswer);\n const members = Object.fromEntries(\n TRANSCRIPT_STATES.map((name) => [name, transcriptHandle[name] as Readable<unknown>])\n ) as Record<(typeof TRANSCRIPT_STATES)[number], Readable<unknown>>;\n const settingsState = settingsHandle.state as Readable<SettingsState>;\n const settings: AgentSettings = {\n ...bound<Omit<AgentSettings, 'state'>>(\n settingsHandle,\n root,\n OWNER_SETTINGS_METHODS,\n settingsAnswer\n ),\n state: replicated(settingsState),\n };\n const remote = bound<AgentRemote>(remoteHandle, root, REMOTE_METHODS, remoteAnswer);\n const pages = bound<AgentPages>(pagesHandle, root, PAGE_METHODS, pageAnswer);\n const state = <K extends keyof typeof members>(name: K) =>\n replicated(members[name] as Readable<never>);\n const held: Lasting<unknown>[] = [];\n const hold = <T>(state: ReplicatedState<T>): ReplicatedState<T> => {\n const kept = lasting(state);\n held.push(kept as Lasting<unknown>);\n return kept.state;\n };\n let open = true;\n const finish = () => {\n if (!open) return;\n open = false;\n for (const kept of held) kept.freeze();\n release();\n };\n const closed = link.ended.then((reason) => {\n finish();\n return reason;\n });\n return {\n serverId,\n readOnly: controlHandle.variant === 'view',\n control,\n transcript: hold<ConversationView>(state('state')),\n deliveries: hold<Record<string, Delivered>>(state('deliveries')),\n agents: hold<AgentsSummary>(state('agents')),\n views: hold<Record<string, ConversationView>>(state('views')),\n commands: hold<Command[]>(state('commands')),\n privateRevision: hold<PrivateRevision>(state('privateRevision')),\n sprinkles: hold<Sprinkle[]>(state('sprinkles')),\n memories: hold<MemoryEntry[]>(state('memories')),\n memoryScopes: hold<MemoryScope[]>(state('memoryScopes')),\n frozen: hold<FrozenCone[]>(state('frozen')),\n importing: hold<ImportProgress>(state('importing')),\n changes: hold<ChangesView>(state('changes')),\n monitor: hold<MonitorFeed>(state('monitor')),\n vault: hold<VaultState>(state('vault')),\n labels: hold<Record<string, string>>(state('labels')),\n guests: hold<GuestSeat[]>(state('guests')),\n viewOnly: controlHandle.variant === 'view',\n owner: pagesHandle.variant === 'pages',\n approvals: hold<Approval[]>(state('approvals')),\n approvalPolicy: hold<ApprovalPolicy>(state('approvalPolicy')),\n settings: lastingSettings(settings, hold),\n remote,\n history: offers(controlHandle, 'entries'),\n pages,\n ...(inventoryHandle?.variant === 'owner'\n ? { inventory: hold(replicated(inventoryHandle.inventory as Readable<InventoryState>)) }\n : {}),\n closed,\n webhook(name, delivery) {\n return control.webhook(\n name,\n { id: delivery.id ?? null, headers: delivery.headers ?? {}, body: delivery.body },\n context\n );\n },\n async prompt(text, whenBusy = 'followUp') {\n const sent = await control.send({ text, whenBusy, requestId: null }, context);\n if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);\n const settled = await control.wait(sent.submissionId, context);\n if (settled.status !== 'done') throw new Error(`unanswered: ${settled.reason}`);\n return settled.text;\n },\n async close() {\n finish();\n link.close('closed');\n await closed;\n await host.close();\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,EAEE;AAAA,EAEA;AAAA,OAGK;AACP,SAAS,0BAA0B;
|
|
4
|
+
"sourcesContent": ["import {\n type Context,\n createHost,\n type Host,\n isChordError,\n type Readable,\n type ReplicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { ApprovalPolicy } from './approvals/policy.ts';\nimport type { Approval } from './approvals/record.ts';\nimport type { Runnable } from './approvals/runnable.ts';\nimport type { ChangesView } from './changes/git.ts';\nimport type { FrozenCone } from './freezer/index.ts';\nimport type { ImportProgress } from './freezer/v6.ts';\nimport type { GuestSeat } from './guests/seats.ts';\nimport type { MemoryEntry, MemoryScope } from './memory/format.ts';\nimport { controlAnswer, pageAnswer, remoteAnswer, settingsAnswer } from './readonly.ts';\nimport type { AgentRemote } from './remote/host.ts';\nimport type { AgentPages } from './remote/pages.ts';\nimport type { VaultState } from './secrets/vault.ts';\nimport {\n AgentControl,\n AgentInventoryService,\n AgentPagesService,\n AgentRemoteService,\n AgentSettings,\n type AgentsSummary,\n AgentTranscript,\n CONTROL_METHODS,\n type Command,\n type Delivered,\n type GuestProposal,\n type GuestShown,\n type InventoryState,\n type MonitorFeed,\n OWNER_SETTINGS_METHODS,\n PAGE_METHODS,\n type PrivateRevision,\n REMOTE_METHODS,\n type SendMode,\n type SettingsState,\n TRANSCRIPT_STATES,\n} from './services.ts';\nimport {\n type AgentPrincipal,\n bound,\n offers,\n type Remote,\n type Root,\n replicated,\n SELF,\n} from './serving.ts';\nimport type { Sprinkle } from './sprinkles/kind.ts';\nimport { otherVersion, type PortEndpoint, PortLink } from './wire.ts';\n\nexport interface AgentConnection {\n readonly serverId: string;\n readonly control: AgentControl;\n readonly transcript: ReplicatedState<ConversationView>;\n readonly deliveries: ReplicatedState<Record<string, Delivered>>;\n readonly agents?: ReplicatedState<AgentsSummary>;\n readonly views?: ReplicatedState<Record<string, ConversationView>>;\n readonly commands?: ReplicatedState<Command[]>;\n readonly privateRevision?: ReplicatedState<PrivateRevision>;\n readonly sprinkles?: ReplicatedState<Sprinkle[]>;\n readonly memories?: ReplicatedState<MemoryEntry[]>;\n readonly memoryScopes?: ReplicatedState<MemoryScope[]>;\n readonly frozen?: ReplicatedState<FrozenCone[]>;\n readonly importing?: ReplicatedState<ImportProgress>;\n readonly changes?: ReplicatedState<ChangesView>;\n readonly monitor?: ReplicatedState<MonitorFeed>;\n readonly vault?: ReplicatedState<VaultState>;\n readonly labels?: ReplicatedState<Record<string, string>>;\n readonly guests?: ReplicatedState<GuestSeat[]>;\n readonly viewOnly?: boolean;\n readonly guest?: GuestShown;\n readonly proposals?: ReplicatedState<GuestProposal[]>;\n readonly owner?: boolean;\n readonly approvals?: ReplicatedState<Approval[]>;\n readonly approvalPolicy?: ReplicatedState<ApprovalPolicy>;\n readonly approvalRunnable?: ReplicatedState<Record<string, Runnable>>;\n readonly settings: AgentSettings;\n readonly remote?: AgentRemote;\n readonly history?: boolean;\n readonly pages?: AgentPages;\n readonly inventory?: ReplicatedState<InventoryState>;\n readonly closed: Promise<Error | undefined>;\n readonly readOnly?: boolean;\n prompt(text: string, whenBusy?: SendMode): Promise<string>;\n webhook(\n name: string,\n delivery: { id?: string | null; headers?: Record<string, string>; body: string }\n ): Promise<{ delivered: boolean }>;\n close(): Promise<void>;\n}\n\nexport interface Lasting<T> {\n readonly state: ReplicatedState<T>;\n freeze(): void;\n}\n\nexport function lasting<T>(state: ReplicatedState<T>): Lasting<T> {\n let last: T | undefined;\n let frozen = false;\n const read = () => {\n if (frozen) return last;\n try {\n last = state.value;\n } catch {}\n return last;\n };\n return {\n state: {\n get value() {\n return read();\n },\n subscribe: (listener) => (frozen ? () => undefined : state.subscribe(listener)),\n },\n freeze() {\n read();\n frozen = true;\n },\n };\n}\n\nexport function lastingSettings(\n settings: AgentSettings,\n hold: <T>(state: ReplicatedState<T>) => ReplicatedState<T>\n): AgentSettings {\n return {\n state: hold(settings.state),\n connect: (providerId, secret, fields, context) =>\n settings.connect(providerId, secret, fields, context),\n disconnect: (providerId, context) => settings.disconnect(providerId, context),\n remove: (providerId, context) => settings.remove(providerId, context),\n serverUrl: (providerId, context) => settings.serverUrl(providerId, context),\n signIn: (providerId, context) => settings.signIn(providerId, context),\n dismissMoved: (context) => settings.dismissMoved(context),\n addServer: (name, entry, context) => settings.addServer(name, entry, context),\n removeServer: (id, context) => settings.removeServer(id, context),\n refusals: (context) => settings.refusals(context),\n };\n}\n\nconst VERSIONS = new Set(['upgrade_required', 'contract_mismatch']);\n\nexport const final = (error: unknown): unknown =>\n isChordError(error) && VERSIONS.has(error.code) ? otherVersion(error) : error;\n\nexport const ended = (link: PortLink): Promise<never> =>\n link.ended.then((reason) => {\n throw reason ?? new Error('the agent closed the link');\n });\n\ntype Contract = Parameters<Host<AgentPrincipal>['get']>[0];\n\nexport function clientHost(link: PortLink, name: string): Host<AgentPrincipal> {\n const host = createHost<AgentPrincipal>({\n name: `${name}:${crypto.randomUUID()}`,\n kind: 'client',\n self: SELF,\n });\n host.connect(link, { principal: SELF, onProtocolMismatch: () => link.mismatched() });\n return host;\n}\n\nexport async function holding(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contracts: readonly Contract[]\n): Promise<Remote[]> {\n const stop = new AbortController();\n const getting = contracts.map(\n (contract) =>\n host.get(contract, {}, { signal: stop.signal }) as Promise<unknown> as Promise<Remote>\n );\n try {\n return await Promise.race([Promise.all(getting), ended(link)]);\n } catch (error) {\n stop.abort();\n for (const got of getting)\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n link.close('handshake failed');\n void host.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function optional(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contract: Contract\n): Promise<Remote | undefined> {\n const got = host.get(contract, {}) as Promise<unknown> as Promise<Remote>;\n return Promise.race([got, ended(link)]).catch(() => {\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n return undefined;\n });\n}\n\nexport async function connectAgent(\n endpoint: PortEndpoint,\n options: { context?: Context } = {}\n): Promise<AgentConnection> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const link = new PortLink(endpoint);\n const serverId = await link.hello;\n const host = clientHost(link, 'follower');\n const inventory = optional(host, link, AgentInventoryService);\n const handles = await holding(host, link, [\n AgentControl,\n AgentTranscript,\n AgentSettings,\n AgentRemoteService,\n AgentPagesService,\n ]).catch((error: unknown) => {\n void inventory.then((handle) => handle?.release());\n throw final(error);\n });\n const [controlHandle, transcriptHandle, settingsHandle, remoteHandle, pagesHandle] = handles as [\n Remote,\n Remote,\n Remote,\n Remote,\n Remote,\n ];\n const inventoryHandle = await inventory;\n const release = () => {\n for (const handle of handles) handle.release();\n inventoryHandle?.release();\n };\n const root: Root = (run, rootOptions) => host.root(run, rootOptions);\n const control = bound<AgentControl>(controlHandle, root, CONTROL_METHODS, controlAnswer);\n const members = Object.fromEntries(\n TRANSCRIPT_STATES.map((name) => [name, transcriptHandle[name] as Readable<unknown>])\n ) as Record<(typeof TRANSCRIPT_STATES)[number], Readable<unknown>>;\n const settingsState = settingsHandle.state as Readable<SettingsState>;\n const settings: AgentSettings = {\n ...bound<Omit<AgentSettings, 'state'>>(\n settingsHandle,\n root,\n OWNER_SETTINGS_METHODS,\n settingsAnswer\n ),\n state: replicated(settingsState),\n };\n const remote = bound<AgentRemote>(remoteHandle, root, REMOTE_METHODS, remoteAnswer);\n const pages = bound<AgentPages>(pagesHandle, root, PAGE_METHODS, pageAnswer);\n const state = <K extends keyof typeof members>(name: K) =>\n replicated(members[name] as Readable<never>);\n const held: Lasting<unknown>[] = [];\n const hold = <T>(state: ReplicatedState<T>): ReplicatedState<T> => {\n const kept = lasting(state);\n held.push(kept as Lasting<unknown>);\n return kept.state;\n };\n let open = true;\n const finish = () => {\n if (!open) return;\n open = false;\n for (const kept of held) kept.freeze();\n release();\n };\n const closed = link.ended.then((reason) => {\n finish();\n return reason;\n });\n return {\n serverId,\n readOnly: controlHandle.variant === 'view',\n control,\n transcript: hold<ConversationView>(state('state')),\n deliveries: hold<Record<string, Delivered>>(state('deliveries')),\n agents: hold<AgentsSummary>(state('agents')),\n views: hold<Record<string, ConversationView>>(state('views')),\n commands: hold<Command[]>(state('commands')),\n privateRevision: hold<PrivateRevision>(state('privateRevision')),\n sprinkles: hold<Sprinkle[]>(state('sprinkles')),\n memories: hold<MemoryEntry[]>(state('memories')),\n memoryScopes: hold<MemoryScope[]>(state('memoryScopes')),\n frozen: hold<FrozenCone[]>(state('frozen')),\n importing: hold<ImportProgress>(state('importing')),\n changes: hold<ChangesView>(state('changes')),\n monitor: hold<MonitorFeed>(state('monitor')),\n vault: hold<VaultState>(state('vault')),\n labels: hold<Record<string, string>>(state('labels')),\n guests: hold<GuestSeat[]>(state('guests')),\n viewOnly: controlHandle.variant === 'view',\n owner: pagesHandle.variant === 'pages',\n approvals: hold<Approval[]>(state('approvals')),\n approvalPolicy: hold<ApprovalPolicy>(state('approvalPolicy')),\n approvalRunnable: hold<Record<string, Runnable>>(state('approvalRunnable')),\n settings: lastingSettings(settings, hold),\n remote,\n history: offers(controlHandle, 'entries'),\n pages,\n ...(inventoryHandle?.variant === 'owner'\n ? { inventory: hold(replicated(inventoryHandle.inventory as Readable<InventoryState>)) }\n : {}),\n closed,\n webhook(name, delivery) {\n return control.webhook(\n name,\n { id: delivery.id ?? null, headers: delivery.headers ?? {}, body: delivery.body },\n context\n );\n },\n async prompt(text, whenBusy = 'followUp') {\n const sent = await control.send({ text, whenBusy, requestId: null }, context);\n if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);\n const settled = await control.wait(sent.submissionId, context);\n if (settled.status !== 'done') throw new Error(`unanswered: ${settled.reason}`);\n return settled.text;\n },\n async close() {\n finish();\n link.close('closed');\n await closed;\n await host.close();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EAEE;AAAA,EAEA;AAAA,OAGK;AACP,SAAS,0BAA0B;AAUnC,SAAS,eAAe,YAAY,cAAc,sBAAsB;AAIxE;AAAA,EACE;AAAA,EAC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ovals = async () => ({
|
|
|
32
32
|
state: null,
|
|
33
33
|
error: "This agent has no approvals."
|
|
34
34
|
});
|
|
35
|
+
const noRun = async () => ({
|
|
36
|
+
done: false,
|
|
37
|
+
error: "This agent has no approvals."
|
|
38
|
+
});
|
|
39
|
+
const noRuns = { approvalRun: noRun, approvalRunStop: noRun };
|
|
35
40
|
function freezerControl(freezer) {
|
|
36
41
|
const needed = () => {
|
|
37
42
|
if (!freezer) throw new Error("This agent has no freezer.");
|
|
@@ -395,7 +400,8 @@ function createAgentControl(harness, target, deliveries, licks, scoops, skills,
|
|
|
395
400
|
agentCommands: async (agentId) => skills?.commandsFor(agentId) ?? [],
|
|
396
401
|
...labelControls(labels),
|
|
397
402
|
entries: pager(conversationFor),
|
|
398
|
-
decide: noApprovals
|
|
403
|
+
decide: noApprovals,
|
|
404
|
+
...noRuns
|
|
399
405
|
};
|
|
400
406
|
}
|
|
401
407
|
export {
|