@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
112 lines • 5.98 kB
JavaScript
import { isAbsolute } from "node:path";
import { createHandFileOps } from "./hand-file-ops.js";
import { loadFlock } from "./hand-flock-binding.js";
import { grantLooplessExecuteToRemoteExecutor } from "./loopless-execute-grant.js";
import { createLooplessRuntimeFactory } from "./runtime-factory-loopless.js";
const handRun = {
context: { uid: process.getuid?.() ?? -1, platform: process.platform, ownEnv: process.env },
flock: loadFlock(),
};
/** What the issuing session sent with a call; an unknown surface is dropped, never read as another one. */
function callFacts(call) {
const surface = call.promptSurface;
return surface === "terminal" || surface === "app" || surface === "chat" ? { promptSurface: surface } : {};
}
function notFound(name) {
return { content: [{ type: "text", text: `Tool ${name} not found` }], details: {}, isError: true };
}
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
function scopeOf(payload) {
const scope = isRecord(payload) ? payload.scope : undefined;
if (!isRecord(scope) || typeof scope.id !== "string" || typeof scope.root !== "string")
throw new Error("a loop-hook call names no scope");
return { id: scope.id, root: scope.root };
}
/**
* Opens a hand's execution scopes on loopless runtimes (brain/hand split, S27a): one runtime per scope, bound to the
* scope's root as its cwd, built with the remote tool executor's grant so every call runs that runtime's extensions'
* `tool_call`/`tool_result` handlers (permission checks among them) around the tool. Nothing about the session reaches
* the runtime: the scope ID and root are all it is opened with. The loop hooks of a scope run on that scope's runtime.
*/
export function createLooplessHand(configuration, local = {}) {
const factory = createLooplessRuntimeFactory(configuration, {
...local,
executeGrant: grantLooplessExecuteToRemoteExecutor(),
});
// One runtime per scope ID, bound to the root it was opened with. A scope's loop hooks need its extensions' state, so
// a loop-hook call never reopens a scope that was disposed (only the remote executor reopens one, with openScope).
const runtimes = new Map();
const disposed = new Set();
let closed = false;
// A runtime is disposed once, whether its scope or close() gets there first.
const disposals = new WeakMap();
const disposeOnce = (runtime) => {
const known = disposals.get(runtime);
if (known !== undefined)
return known;
const disposing = runtime.dispose();
disposals.set(runtime, disposing);
return disposing;
};
const runtimeOf = (scope, reopen) => {
if (closed)
return Promise.reject(new Error("this hand is closed"));
if (!isAbsolute(scope.root))
return Promise.reject(new Error(`scope root must be an absolute path: ${JSON.stringify(scope.root)}`));
const known = runtimes.get(scope.id);
if (known !== undefined)
return known.root === scope.root
? known.runtime
: Promise.reject(new Error(`scope_binding_mismatch: scope ${JSON.stringify(scope.id)} is bound to another root`));
if (!reopen && disposed.has(scope.id))
return Promise.reject(new Error(`scope ${JSON.stringify(scope.id)} was disposed; its extensions' loop-hook state is gone`));
disposed.delete(scope.id);
const { wakes } = local;
const opened = factory({
cwd: scope.root,
...(wakes === undefined ? {} : { wake: (wake) => wakes.offer(scope.id, wake) }),
});
runtimes.set(scope.id, { root: scope.root, runtime: opened });
opened.catch(() => runtimes.delete(scope.id));
return opened;
};
return {
async openScope(scope) {
const runtime = await runtimeOf(scope, true);
return {
run: (call) => runtime.definitions.has(call.name)
? runtime.execute(call.name, call.toolCallId, call.arguments, call.signal, call.nested, callFacts(call))
: Promise.resolve(notFound(call.name)),
isSequential: (name) => runtime.definitions.get(name)?.definition.executionMode === "sequential",
...(runtime.fileGuards === undefined
? {}
: { file: createHandFileOps(scope.root, runtime.fileGuards, handRun) }),
dispose: () => {
runtimes.delete(scope.id);
disposed.add(scope.id);
local.wakes?.closeScope(scope.id);
return disposeOnce(runtime);
},
};
},
runLoopHooks: async (scope, event, payload) => (await runtimeOf(scope, false)).runLoopHooks(event, payload),
loopHooks: async (event, payload) => (await runtimeOf(scopeOf(payload), false)).runLoopHooks(event, payload),
async close() {
closed = true;
const open = [...runtimes.values()];
runtimes.clear();
// Every disposal runs to its end; a runtime that never opened has nothing to dispose.
const settled = await Promise.allSettled(open.map(({ runtime }) => runtime.then((opened) => disposeOnce(opened), () => undefined)));
const failures = settled.flatMap((outcome) => (outcome.status === "rejected" ? [outcome.reason] : []));
if (failures.length === 1)
throw failures[0];
if (failures.length > 1)
throw new AggregateError(failures, "disposing this hand's runtimes failed");
},
};
}
/** The scopes of {@link createLooplessHand}, for a hand that serves no loop hooks. */
export function createLooplessHandScopes(configuration, local = {}) {
return createLooplessHand(configuration, local).openScope;
}
//# sourceMappingURL=remote-executor-scope.js.map