omp-superagent 0.1.5 → 0.1.6
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/DESIGN.md +62 -8
- package/README.ko.md +22 -14
- package/README.md +36 -22
- package/config.example.json +1 -0
- package/docs/OPERATIONS.md +180 -42
- package/docs/design/execution.md +20 -7
- package/docs/design/messaging.md +131 -11
- package/docs/releases/0.1.6.md +21 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +1 -1
- package/skills/head/SKILL.md +7 -2
- package/skills/head/references/model-selection.md +4 -4
- package/skills/head/references/routing.md +9 -4
- package/skills/head/references/supervision.md +4 -3
- package/skills/lane/SKILL.md +19 -13
- package/skills/lane/references/workflow.md +19 -11
- package/src/board.ts +7 -2
- package/src/cli.ts +22 -6
- package/src/config.ts +26 -3
- package/src/contracts.ts +20 -2
- package/src/decision-tool.ts +1 -1
- package/src/extension.ts +40 -2
- package/src/gateway-client.ts +22 -1
- package/src/gateway-config.ts +4 -4
- package/src/gateway-restart-env.ts +7 -2
- package/src/gateway-wire.ts +8 -0
- package/src/group-access.ts +222 -0
- package/src/group-policy.ts +117 -0
- package/src/group-runner-extension.ts +153 -0
- package/src/group-runner.ts +284 -0
- package/src/head-rotation.ts +88 -0
- package/src/host-extension.ts +52 -3
- package/src/host-protocol.ts +1 -0
- package/src/host-sdk-helper.ts +7 -0
- package/src/host-superkit.ts +26 -0
- package/src/host.ts +5 -1
- package/src/lane-extension.ts +6 -3
- package/src/managed-memory-helper.ts +22 -0
- package/src/managed-memory.ts +100 -0
- package/src/managed-ulw.ts +16 -20
- package/src/messenger-command-catalog.json +3 -2
- package/src/native-launch-profile.ts +16 -0
- package/src/native-settings.ts +9 -3
- package/src/result-attachment.ts +211 -0
- package/src/runtime.ts +1109 -157
- package/src/setup-memory.ts +15 -33
- package/src/setup.ts +24 -22
- package/src/store.ts +214 -13
- package/src/topic-history.ts +430 -0
- package/src/topic-request.ts +88 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
|
|
2
|
+
import { Type, type Static } from "@sinclair/typebox";
|
|
3
|
+
import { Value } from "@sinclair/typebox/value";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { credentialEnvNames, type Config } from "./config";
|
|
6
|
+
|
|
7
|
+
const nativeScope = {
|
|
8
|
+
source: Type.Union([Type.Literal("default"), Type.Literal("global"), Type.Literal("project"),
|
|
9
|
+
Type.Literal("overlay"), Type.Literal("env"), Type.Literal("runtime")]),
|
|
10
|
+
agentDir: Type.String(),
|
|
11
|
+
};
|
|
12
|
+
const enabledMemory = Type.Object({ ...nativeScope, status: Type.Literal("enabled"), backend: Type.Literal("mnemopi") });
|
|
13
|
+
const missingMemory = Type.Object({
|
|
14
|
+
...nativeScope,
|
|
15
|
+
status: Type.Literal("missing"),
|
|
16
|
+
backend: Type.Union([Type.Literal("off"), Type.Literal("local"), Type.Literal("hindsight"),
|
|
17
|
+
Type.Literal("sharpshooter")]),
|
|
18
|
+
});
|
|
19
|
+
const memoryStatus = Type.Union([enabledMemory, missingMemory, Type.Object({
|
|
20
|
+
status: Type.Union([Type.Literal("legacy"), Type.Literal("unknown")]),
|
|
21
|
+
})]);
|
|
22
|
+
const overlayUnset = Type.Object({ backend: Type.Null() });
|
|
23
|
+
const memoryReport = Type.Object({ memory: memoryStatus, updated: Type.Boolean() });
|
|
24
|
+
export type MnemopiStatus = Static<typeof memoryStatus>;
|
|
25
|
+
export type MnemopiReport = Static<typeof memoryReport>;
|
|
26
|
+
type GlobalMemoryCandidate = Static<typeof missingMemory> & { source: "default" | "global" };
|
|
27
|
+
|
|
28
|
+
export async function effectiveMnemopi(settings: Settings): Promise<MnemopiStatus> {
|
|
29
|
+
const { cfgMemoryBackend } = await import("@oh-my-pi/pi-coding-agent/memory-backend/settings");
|
|
30
|
+
// The RPC soft pin uses this setting's own schema default when unconfigured.
|
|
31
|
+
// Do not write a runtime override to the read-only snapshot used for consent.
|
|
32
|
+
const backend = cfgMemoryBackend.get(settings);
|
|
33
|
+
const agentDir = settings.getAgentDir();
|
|
34
|
+
let source = cfgMemoryBackend.provenance(settings);
|
|
35
|
+
if (source === "default") {
|
|
36
|
+
// Stock provenance describes the value, not an explicit overlay tombstone.
|
|
37
|
+
// An overlay unset must not make setup offer an ineffectual global edit.
|
|
38
|
+
const { memory } = settings.mirrorState().configOverlay;
|
|
39
|
+
if (memory === null || Value.Check(overlayUnset, memory)) {
|
|
40
|
+
source = "overlay";
|
|
41
|
+
} else {
|
|
42
|
+
const { hasUnresolvedNativeLegacy } = await import("./native-settings");
|
|
43
|
+
if (await hasUnresolvedNativeLegacy(agentDir)) return { status: "legacy" };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return backend === "mnemopi" ? { status: "enabled", backend, source, agentDir }
|
|
47
|
+
: { status: "missing", backend, source, agentDir };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function canEnableGlobalMemory(memory: MnemopiStatus): memory is GlobalMemoryCandidate {
|
|
51
|
+
return memory.status === "missing" && (memory.source === "default" || memory.source === "global");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function parseMemoryConsent(bytes: string): MnemopiStatus {
|
|
55
|
+
const value: unknown = JSON.parse(bytes);
|
|
56
|
+
if (!Value.Check(memoryStatus, value) || !canEnableGlobalMemory(value))
|
|
57
|
+
throw new Error("Expected consent to repair the current global memory preference");
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function memoryBlockReason(memory: MnemopiStatus): string {
|
|
62
|
+
const requirement = "Managed sessions require effective native OMP Mnemopi (memory.backend=mnemopi).";
|
|
63
|
+
switch (memory.status) {
|
|
64
|
+
case "enabled": return "";
|
|
65
|
+
case "unknown": return `${requirement} Native memory settings could not be verified; inspect the selected profile and launch overlays.`;
|
|
66
|
+
case "legacy": return `${requirement} Unmigrated native settings could not be verified; migrate them with ordinary stock OMP in the selected profile first.`;
|
|
67
|
+
case "missing": return `${requirement} Effective backend is ${memory.backend} (${memory.source} settings). ${
|
|
68
|
+
canEnableGlobalMemory(memory) ? "Run interactive setup or configure the selected native profile."
|
|
69
|
+
: "Review the overriding native settings for this workspace; Superagent does not change them."}`;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function inspectManagedMnemopi(config: Config): Promise<MnemopiStatus> {
|
|
74
|
+
return (await runMemoryHelper(config)).memory;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function applyConsentedMnemopi(config: Config, consent: GlobalMemoryCandidate): Promise<MnemopiReport> {
|
|
78
|
+
return runMemoryHelper(config, consent);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function runMemoryHelper(config: Config, consent?: GlobalMemoryCandidate): Promise<MnemopiReport> {
|
|
82
|
+
const env = { ...process.env };
|
|
83
|
+
for (const name of credentialEnvNames(config)) delete env[name];
|
|
84
|
+
const helper = fileURLToPath(new URL("./managed-memory-helper.ts", import.meta.url));
|
|
85
|
+
const unavailable: MnemopiReport = { memory: { status: "unknown" }, updated: false };
|
|
86
|
+
try {
|
|
87
|
+
const operation = consent ? "apply-consented" : "inspect";
|
|
88
|
+
const child = Bun.spawn([process.execPath, "--no-env-file", "--no-install", helper, operation, ...config.command.slice(1)], {
|
|
89
|
+
cwd: config.headCwd, env, stdin: consent ? new Blob([JSON.stringify(consent)]) : "ignore",
|
|
90
|
+
stdout: "pipe", stderr: "ignore", timeout: 30_000, killSignal: "SIGKILL",
|
|
91
|
+
});
|
|
92
|
+
const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
|
|
93
|
+
if (code !== 0) return unavailable;
|
|
94
|
+
const line = stdout.split("\n").findLast(value => value.startsWith("MANAGED_MEMORY "));
|
|
95
|
+
const parsed: unknown = line && JSON.parse(line.slice("MANAGED_MEMORY ".length));
|
|
96
|
+
return Value.Check(memoryReport, parsed) ? parsed : unavailable;
|
|
97
|
+
} catch {
|
|
98
|
+
return unavailable;
|
|
99
|
+
}
|
|
100
|
+
}
|
package/src/managed-ulw.ts
CHANGED
|
@@ -79,19 +79,23 @@ function readActive(root: string): ActiveRevision | null {
|
|
|
79
79
|
return value;
|
|
80
80
|
} catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
|
|
81
81
|
}
|
|
82
|
-
export function
|
|
82
|
+
export function readManagedUlwPackage(packagePath: string) {
|
|
83
83
|
if (!isAbsolute(packagePath)) throw new Error("Managed ULW package must have an absolute path");
|
|
84
84
|
const canonical = realpathSync(packagePath);
|
|
85
85
|
const pkg = JSON.parse(readFileSync(join(canonical, "package.json"), "utf8")) as PackageManifest;
|
|
86
86
|
if (!isManagedUlwPackageName(pkg.name) || !Array.isArray(pkg.omp?.extensions) || !pkg.omp.extensions.length)
|
|
87
87
|
throw new Error("Managed ULW package has no native extension manifest");
|
|
88
|
-
|
|
88
|
+
const extensionFiles = pkg.omp.extensions.map(entry => {
|
|
89
89
|
if (typeof entry !== "string" || !entry || isAbsolute(entry)) throw new Error("Invalid managed ULW extension entry");
|
|
90
90
|
const target = realpathSync(resolve(canonical, entry));
|
|
91
91
|
if (!target.startsWith(canonical + sep) || !lstatSync(target).isFile()) throw new Error("Managed ULW extension leaves its package");
|
|
92
|
-
|
|
92
|
+
return target;
|
|
93
|
+
});
|
|
93
94
|
if (!lstatSync(join(canonical, "skills")).isDirectory()) throw new Error("Managed ULW skills are missing");
|
|
94
|
-
return canonical;
|
|
95
|
+
return { packagePath: canonical, extensionFiles };
|
|
96
|
+
}
|
|
97
|
+
export function validateManagedUlwPackage(packagePath: string): string {
|
|
98
|
+
return readManagedUlwPackage(packagePath).packagePath;
|
|
95
99
|
}
|
|
96
100
|
export function activeManagedUlw(options: ManagedUlwOptions = {}): string {
|
|
97
101
|
const root = rootFor(options);
|
|
@@ -211,21 +215,11 @@ if (import.meta.main && process.argv[2] === "--launch-extensions") {
|
|
|
211
215
|
cwd: string; managedUlwPath: string; extensionPaths: string[]; configPath: string;
|
|
212
216
|
commandArgs: string[]; launchArgs: string[];
|
|
213
217
|
};
|
|
214
|
-
|
|
215
|
-
|
|
218
|
+
const { parseNativeLaunch } = await import("./native-launch-profile");
|
|
219
|
+
const parsed = await parseNativeLaunch(input.launchArgs);
|
|
216
220
|
const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
|
|
217
|
-
const {
|
|
218
|
-
const bootstrap = extractProfileFlags(input.launchArgs);
|
|
219
|
-
setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
|
|
220
|
-
if (bootstrap.aliasName !== undefined) throw new Error("Managed ULW discovery requires a launch, not --alias installation");
|
|
221
|
-
const { isNativeShell } = await import("@oh-my-pi/pi-coding-agent/cli/native-shell");
|
|
222
|
-
if (isNativeShell(bootstrap.argv[0])) throw new Error("Managed ULW discovery requires native OMP launch argv, not a shell command");
|
|
223
|
-
const { resolveCliArgv } = await import("@oh-my-pi/pi-coding-agent/cli-commands");
|
|
224
|
-
const resolved = resolveCliArgv(bootstrap.argv);
|
|
225
|
-
if ("error" in resolved) throw new Error(resolved.error);
|
|
226
|
-
if (resolved.argv[0] !== "launch") throw new Error("Managed ULW discovery requires native OMP launch argv");
|
|
221
|
+
const { getProjectDir } = await import("@oh-my-pi/pi-utils/dirs");
|
|
227
222
|
const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
|
|
228
|
-
const parsed = parseArgs(resolved.argv.slice(1));
|
|
229
223
|
const command = parseArgs(extractProfileFlags(input.commandArgs).argv);
|
|
230
224
|
if (parsed.trustedExtensions?.length) {
|
|
231
225
|
throw new Error("Stock OMP --trusted-extension cannot preserve managed ULW package resources");
|
|
@@ -246,9 +240,11 @@ if (import.meta.main && process.argv[2] === "--launch-extensions") {
|
|
|
246
240
|
const { homedir } = await import("node:os");
|
|
247
241
|
if (parsed.pluginDirs?.length) await injectPluginDirRoots(homedir(), parsed.pluginDirs, cwd);
|
|
248
242
|
else await preloadPluginRoots(homedir(), cwd);
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
243
|
+
const { effectiveMnemopi, memoryBlockReason } = await import("./managed-memory");
|
|
244
|
+
const settings = await Settings.loadReadOnly({ cwd, agentDir: getAgentDir(), configFiles: parsed.config })
|
|
245
|
+
.catch(() => { throw new Error(memoryBlockReason({ status: "unknown" })); });
|
|
246
|
+
const memory = await effectiveMnemopi(settings).catch(() => ({ status: "unknown" } as const));
|
|
247
|
+
if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
|
|
252
248
|
const restore = initializeWithSettings(settings);
|
|
253
249
|
try {
|
|
254
250
|
const managed = validateManagedUlwPackage(input.managedUlwPath);
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
[
|
|
2
2
|
{ "name": "help", "description": "Show Superagent commands and their scope." },
|
|
3
|
+
{ "name": "head", "description": "Send a request to the global Superagent coordination session.", "text": "Request for the global head, for example to compare two work topics." },
|
|
3
4
|
{ "name": "status", "description": "Inspect Superagent HEAD and this conversation's lane, including while busy." },
|
|
4
|
-
{ "name": "restart", "description": "
|
|
5
|
+
{ "name": "restart", "description": "Interrupt HEAD work and restart Superagent Gateway and HEAD with the same session and memory." },
|
|
5
6
|
{ "name": "context", "description": "Inspect Superagent HEAD context without starting a model turn." },
|
|
6
7
|
{ "name": "usage", "description": "Show Superagent's OMP account quotas and reset times." },
|
|
7
8
|
{ "name": "cron", "description": "Schedule and manage Superagent jobs in this conversation.", "text": "Use help, add, list, show, edit, pause, resume, run or remove." },
|
|
@@ -12,5 +13,5 @@
|
|
|
12
13
|
{ "name": "effort", "description": "Choose the Superagent HEAD thinking effort.", "text": "Omit for the menu, or enter an exact advertised effort level." },
|
|
13
14
|
{ "name": "compact", "description": "Compact Superagent HEAD context when idle.", "text": "Optional compaction instructions, including multiple lines." },
|
|
14
15
|
{ "name": "stop", "description": "Stop Superagent HEAD work or pause a bound or explicitly named lane.", "text": "head or an actual lane ID; omit to use this conversation's lane, otherwise HEAD." },
|
|
15
|
-
{ "name": "new", "description": "Start a
|
|
16
|
+
{ "name": "new", "description": "Start a Superagent work topic; use a sibling for a new request in an existing thread.", "text": "An optional first request for the new topic." }
|
|
16
17
|
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Stock OMP chooses its profile before settings or discovery import native dotenv. */
|
|
2
|
+
export async function parseNativeLaunch(launchArgs: readonly string[]) {
|
|
3
|
+
const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
|
|
4
|
+
const { setProfile, resolveProfileEnv } = await import("@oh-my-pi/pi-utils/dirs");
|
|
5
|
+
const bootstrap = extractProfileFlags(launchArgs);
|
|
6
|
+
setProfile(bootstrap.profile ?? resolveProfileEnv(process.env.OMP_PROFILE, process.env.PI_PROFILE));
|
|
7
|
+
if (bootstrap.aliasName !== undefined) throw new Error("Managed Hosts cannot install native aliases");
|
|
8
|
+
const { isNativeShell } = await import("@oh-my-pi/pi-coding-agent/cli/native-shell");
|
|
9
|
+
if (isNativeShell(bootstrap.argv[0])) throw new Error("Managed Hosts require native launch argv, not a shell command");
|
|
10
|
+
const { resolveCliArgv } = await import("@oh-my-pi/pi-coding-agent/cli-commands");
|
|
11
|
+
const resolved = resolveCliArgv(bootstrap.argv);
|
|
12
|
+
if ("error" in resolved) throw new Error(resolved.error);
|
|
13
|
+
if (resolved.argv[0] !== "launch") throw new Error("Managed Hosts require native OMP launch argv");
|
|
14
|
+
const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
|
|
15
|
+
return parseArgs(resolved.argv.slice(1));
|
|
16
|
+
}
|
package/src/native-settings.ts
CHANGED
|
@@ -62,7 +62,7 @@ function valueAt(record: unknown, path: readonly string[]): unknown {
|
|
|
62
62
|
* A stale key is preserved while disjoint keys are merged from the locked file.
|
|
63
63
|
*/
|
|
64
64
|
export async function editNativeGlobalConfig(settings: Settings, edits: readonly GlobalEdit[],
|
|
65
|
-
accept?: (actual: Settings) => boolean): Promise<boolean[]> {
|
|
65
|
+
accept?: (actual: Settings) => boolean | Promise<boolean>): Promise<boolean[]> {
|
|
66
66
|
const agentDir = settings.getAgentDir();
|
|
67
67
|
if (await hasUnresolvedNativeLegacy(agentDir)) throw new Error("Native global settings require legacy migration");
|
|
68
68
|
let configPath = join(agentDir, MAIN_CONFIG_FILENAMES[0]);
|
|
@@ -87,7 +87,7 @@ export async function editNativeGlobalConfig(settings: Settings, edits: readonly
|
|
|
87
87
|
return withFileLock(writePath, async () => {
|
|
88
88
|
const actual = await readNativeSettings(settings);
|
|
89
89
|
if (await hasUnresolvedNativeLegacy(agentDir)) throw new Error("Native global settings require legacy migration");
|
|
90
|
-
if (accept && !accept(actual)) return edits.map(() => false);
|
|
90
|
+
if (accept && !await accept(actual)) return edits.map(() => false);
|
|
91
91
|
for (const filename of MAIN_CONFIG_FILENAMES) {
|
|
92
92
|
const candidate = join(agentDir, filename);
|
|
93
93
|
if (await isPresent(candidate)) {
|
|
@@ -105,6 +105,7 @@ export async function editNativeGlobalConfig(settings: Settings, edits: readonly
|
|
|
105
105
|
if (raw === null || raw === undefined) raw = {};
|
|
106
106
|
if (!isRecord(raw)) throw new Error("Native global config must be a mapping");
|
|
107
107
|
const global = raw;
|
|
108
|
+
const actualGlobal = actual.getGlobalSettings();
|
|
108
109
|
const updated = structuredClone(global);
|
|
109
110
|
const applied = edits.map(edit => {
|
|
110
111
|
const path = edit.path.split(".");
|
|
@@ -114,7 +115,12 @@ export async function editNativeGlobalConfig(settings: Settings, edits: readonly
|
|
|
114
115
|
actual.getOwnedModelPreset(name) ||
|
|
115
116
|
[actual.mirrorState().overrides, actual.mirrorState().configOverlay].some(layer =>
|
|
116
117
|
isRecord(layer.modelPresets) && Object.hasOwn(layer.modelPresets, name))) return false;
|
|
117
|
-
} else
|
|
118
|
+
} else {
|
|
119
|
+
// Native Settings interprets legacy `memories.enabled` in modern YAML
|
|
120
|
+
// as a backend. Compare that effective global value while editing raw YAML.
|
|
121
|
+
const latest = edit.path === "memory.backend" ? actualGlobal : global;
|
|
122
|
+
if (!Bun.deepEquals(valueAt(latest, path), valueAt(baseline, path))) return false;
|
|
123
|
+
}
|
|
118
124
|
let target = updated;
|
|
119
125
|
for (const segment of path.slice(0, -1)) {
|
|
120
126
|
if (!isRecord(target[segment])) target[segment] = {};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { constants, fstatSync, lstatSync, openSync, closeSync, readSync, realpathSync } from "node:fs";
|
|
2
|
+
import { basename, isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
|
|
4
|
+
import { Type } from "@sinclair/typebox";
|
|
5
|
+
import type { Inbound } from "./contracts";
|
|
6
|
+
|
|
7
|
+
const MAX_RESULT_ATTACHMENT_BYTES = 8 * 1024 * 1024;
|
|
8
|
+
export const RESULT_ATTACH_TOOL = "result_attach";
|
|
9
|
+
|
|
10
|
+
export interface ResultAttachmentPayload {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly data: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface NativeSession {
|
|
16
|
+
readonly sessionId: string;
|
|
17
|
+
readonly sessionFile: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface AttachmentArgs {
|
|
21
|
+
readonly sourceId: string;
|
|
22
|
+
readonly path: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ResultAttachmentIntent extends NativeSession, AttachmentArgs {
|
|
26
|
+
readonly toolCallId: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface StagedResultAttachment extends NativeSession {
|
|
30
|
+
readonly payload: ResultAttachmentPayload;
|
|
31
|
+
readonly sourceId: string;
|
|
32
|
+
readonly inputId: string;
|
|
33
|
+
readonly requestId: string;
|
|
34
|
+
readonly generation: number;
|
|
35
|
+
readonly toolCallId: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class ResultAttachmentError extends Error {
|
|
39
|
+
override readonly name = "ResultAttachmentError";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function validPath(path: string): boolean {
|
|
43
|
+
return path.length <= 1024 && !isAbsolute(path) && !/[\p{Cc}\p{Cf}\\]/u.test(path)
|
|
44
|
+
&& path.split("/").every(part => part.length > 0 && !part.startsWith(".") && part === part.trim());
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Only a leading literal directive in the owner message is consent. */
|
|
48
|
+
export function requestedResultPath(text: string): string | null {
|
|
49
|
+
const request = text.trimStart().replace(/^\/(?:head|new)(?:\s+|$)/, "");
|
|
50
|
+
const path = /^(?:cwd:[ \t]*[^\r\n]*\r?\n)?[ \t]*attach:[ \t]+([^\r\n]+)\r?(?:\n|$)/i.exec(request)?.[1];
|
|
51
|
+
return path && validPath(path) ? path : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Use the native adapters' durable original-revision identities. */
|
|
55
|
+
export function isOriginalAttachmentMessage({ id, messageId, route }: Inbound): boolean {
|
|
56
|
+
if (!messageId) return false;
|
|
57
|
+
return id === (route.platform === "discord"
|
|
58
|
+
? `discord:${route.accountId}:${messageId}:original`
|
|
59
|
+
: `${route.platform}:${route.accountId}:${route.channelId}:${messageId}:original`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function inside(root: string, file: string): boolean {
|
|
63
|
+
const delta = relative(root, file);
|
|
64
|
+
return delta === "" || delta !== ".." && !delta.startsWith(`..${sep}`) && !isAbsolute(delta);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Store the bytes, not a mutable file path to be opened later by the Gateway. */
|
|
68
|
+
export function stageResultAttachment(path: string, scope: {
|
|
69
|
+
readonly cwd: string;
|
|
70
|
+
readonly privatePaths: readonly string[];
|
|
71
|
+
}): ResultAttachmentPayload {
|
|
72
|
+
try {
|
|
73
|
+
if (!validPath(path)) throw new ResultAttachmentError("Use a literal, non-hidden workspace-relative file path");
|
|
74
|
+
const root = resolve(scope.cwd);
|
|
75
|
+
if (realpathSync(root) !== root) throw new ResultAttachmentError("The canonical workspace root has changed");
|
|
76
|
+
const originalRoot = lstatSync(root, { bigint: true });
|
|
77
|
+
const file = resolve(root, path);
|
|
78
|
+
const name = basename(file);
|
|
79
|
+
if (Buffer.byteLength(name) > 180 || !/^[\p{L}\p{N}\p{M}_. -]+$/u.test(name))
|
|
80
|
+
throw new ResultAttachmentError("The result attachment has an unsupported filename");
|
|
81
|
+
const privateEntries = scope.privatePaths.map(privatePath => {
|
|
82
|
+
let canonical = resolve(privatePath);
|
|
83
|
+
try {
|
|
84
|
+
canonical = realpathSync(canonical);
|
|
85
|
+
return { canonical, stat: lstatSync(canonical, { bigint: true }) };
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
88
|
+
return { canonical };
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
const checkPrivate = () => {
|
|
92
|
+
if (realpathSync(root) !== root) throw new ResultAttachmentError("The canonical workspace root has changed");
|
|
93
|
+
const rootStat = lstatSync(root, { bigint: true });
|
|
94
|
+
if (rootStat.dev !== originalRoot.dev || rootStat.ino !== originalRoot.ino)
|
|
95
|
+
throw new ResultAttachmentError("The canonical workspace root has changed");
|
|
96
|
+
if (privateEntries.some(entry => inside(entry.canonical, file)))
|
|
97
|
+
throw new ResultAttachmentError("Private state cannot be sent as a result attachment");
|
|
98
|
+
// Also compare filesystem identities (e.g. case-insensitive volumes).
|
|
99
|
+
let current = root;
|
|
100
|
+
for (const part of ["", ...path.split("/")]) {
|
|
101
|
+
current = resolve(current, part);
|
|
102
|
+
const stat = lstatSync(current, { bigint: true });
|
|
103
|
+
if (stat.isSymbolicLink()) throw new ResultAttachmentError("Result attachment paths cannot follow links");
|
|
104
|
+
if (privateEntries.some(entry => entry.stat?.dev === stat.dev && entry.stat.ino === stat.ino))
|
|
105
|
+
throw new ResultAttachmentError("Private state cannot be sent as a result attachment");
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
checkPrivate();
|
|
109
|
+
if (realpathSync(file) !== file) throw new ResultAttachmentError("Result attachment paths cannot follow links");
|
|
110
|
+
// lstat and the identity checks pin the observed directory entry to the
|
|
111
|
+
// descriptor. Nonblocking open cannot hang if it is replaced with a FIFO.
|
|
112
|
+
const initial = lstatSync(file, { bigint: true });
|
|
113
|
+
if (!initial.isFile() || initial.nlink !== 1n)
|
|
114
|
+
throw new ResultAttachmentError("A result attachment must be a regular file without hard links");
|
|
115
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
116
|
+
try {
|
|
117
|
+
const same = (stat: typeof initial) => stat.isFile() && stat.nlink === 1n
|
|
118
|
+
&& stat.dev === initial.dev && stat.ino === initial.ino && stat.size === initial.size
|
|
119
|
+
&& stat.mtimeNs === initial.mtimeNs && stat.ctimeNs === initial.ctimeNs;
|
|
120
|
+
if (!same(fstatSync(fd, { bigint: true }))) throw new ResultAttachmentError("The attachment changed before staging");
|
|
121
|
+
if (initial.size < 1n || initial.size > MAX_RESULT_ATTACHMENT_BYTES)
|
|
122
|
+
throw new ResultAttachmentError("Result attachments must be nonempty and at most 8 MiB");
|
|
123
|
+
const bytes = Buffer.allocUnsafe(Number(initial.size));
|
|
124
|
+
let offset = 0;
|
|
125
|
+
while (offset < bytes.length) {
|
|
126
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
127
|
+
if (!count) break;
|
|
128
|
+
offset += count;
|
|
129
|
+
}
|
|
130
|
+
if (offset !== bytes.length || !same(fstatSync(fd, { bigint: true }))
|
|
131
|
+
|| realpathSync(file) !== file || !same(lstatSync(file, { bigint: true }))) {
|
|
132
|
+
throw new ResultAttachmentError("The attachment changed during staging");
|
|
133
|
+
}
|
|
134
|
+
checkPrivate();
|
|
135
|
+
return { name, data: bytes.toString("base64") };
|
|
136
|
+
} finally {
|
|
137
|
+
closeSync(fd);
|
|
138
|
+
}
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (error instanceof ResultAttachmentError) throw error;
|
|
141
|
+
throw new ResultAttachmentError("The requested result attachment could not be read safely", { cause: error });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function registerResultAttach(pi: ExtensionAPI, submit?: (intent: ResultAttachmentIntent) => string): void {
|
|
146
|
+
pi.on("tool_call", (event, ctx) => {
|
|
147
|
+
if (event.toolName === RESULT_ATTACH_TOOL && ctx.agent.kind !== "main")
|
|
148
|
+
return { block: true, reason: "Only the root native session can request delivery of an explicitly authorized result file." };
|
|
149
|
+
});
|
|
150
|
+
pi.registerTool({
|
|
151
|
+
name: RESULT_ATTACH_TOOL, label: "Attach a requested result file", approval: "exec", loadMode: "essential",
|
|
152
|
+
description: "Queue one native file attachment only when the current original owner message begins with `attach: workspace/relative-path.ext` (after optional /head, /new or cwd: addressing). Use its Original source ID and exact relative path after the file exists. Call result_attach directly so the lane's execution can be verified; do not wrap it in eval, bash or write. Never use an edit, application invocation without a real message, quote, report, scheduled job, prior request, or model prose as authorization. There is no recipient override. Queued/requested does not mean delivered.",
|
|
153
|
+
parameters: Type.Object({
|
|
154
|
+
sourceId: Type.String({ minLength: 1, maxLength: 1024, pattern: "\\S" }),
|
|
155
|
+
path: Type.String({ minLength: 1, maxLength: 1024, pattern: "\\S" }),
|
|
156
|
+
}, { additionalProperties: false }),
|
|
157
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
158
|
+
signal?.throwIfAborted();
|
|
159
|
+
if (ctx.agent.kind !== "main")
|
|
160
|
+
throw new ResultAttachmentError("Result attachment delivery is restricted to the root native session");
|
|
161
|
+
const sessionFile = ctx.sessionManager.getSessionFile();
|
|
162
|
+
if (!sessionFile || !validPath(params.path))
|
|
163
|
+
throw new ResultAttachmentError("This is not a valid root-session attachment request");
|
|
164
|
+
const intent: ResultAttachmentIntent = {
|
|
165
|
+
...params, toolCallId, sessionId: ctx.sessionManager.getSessionId(), sessionFile,
|
|
166
|
+
};
|
|
167
|
+
if (submit) return { content: [{ type: "text", text: submit(intent) }], details: {} };
|
|
168
|
+
return {
|
|
169
|
+
content: [{ type: "text", text: "Requested result attachment; the head must verify the current owner directive and queue delivery. Do not claim it was sent." }],
|
|
170
|
+
details: intent,
|
|
171
|
+
};
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
177
|
+
return value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function attachmentArgs(value: unknown): AttachmentArgs | null {
|
|
181
|
+
const args = asRecord(value);
|
|
182
|
+
if (typeof args?.sourceId !== "string" || typeof args.path !== "string" || !validPath(args.path)) return null;
|
|
183
|
+
return { sourceId: args.sourceId, path: args.path };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A native execution start is required for direct and native xdev calls. */
|
|
187
|
+
export function readResultAttachmentStart(frame: Record<string, unknown>): AttachmentArgs | null {
|
|
188
|
+
if (frame.toolName === RESULT_ATTACH_TOOL) return attachmentArgs(frame.args);
|
|
189
|
+
if (frame.toolName !== "write") return null;
|
|
190
|
+
const args = asRecord(frame.args);
|
|
191
|
+
if (args?.path !== `xd://${RESULT_ATTACH_TOOL}` ||
|
|
192
|
+
typeof args.content !== "string" || args.content.length > 8192) return null;
|
|
193
|
+
try { return attachmentArgs(JSON.parse(args.content)); }
|
|
194
|
+
catch (error) { if (!(error instanceof SyntaxError)) throw error; return null; }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Parse only a live successful native tool execution result, never prose. */
|
|
198
|
+
export function readResultAttachmentIntent(frame: Record<string, unknown>): ResultAttachmentIntent | null {
|
|
199
|
+
if (frame.isError !== false) return null;
|
|
200
|
+
const details = asRecord(asRecord(frame.result)?.details);
|
|
201
|
+
const xdev = asRecord(details?.xdev);
|
|
202
|
+
const intent = frame.toolName === RESULT_ATTACH_TOOL ? details
|
|
203
|
+
: frame.toolName === "write" && xdev?.tool === RESULT_ATTACH_TOOL && xdev.mode === "execute" ? xdev.inner : null;
|
|
204
|
+
if (!intent || typeof intent !== "object" || !("toolCallId" in intent) ||
|
|
205
|
+
!("sourceId" in intent) || !("path" in intent) || !("sessionId" in intent) || !("sessionFile" in intent) ||
|
|
206
|
+
typeof intent.toolCallId !== "string" || intent.toolCallId !== frame.toolCallId ||
|
|
207
|
+
typeof intent.sourceId !== "string" || typeof intent.path !== "string" ||
|
|
208
|
+
typeof intent.sessionId !== "string" || typeof intent.sessionFile !== "string") return null;
|
|
209
|
+
return { toolCallId: intent.toolCallId, sourceId: intent.sourceId, path: intent.path,
|
|
210
|
+
sessionId: intent.sessionId, sessionFile: intent.sessionFile };
|
|
211
|
+
}
|