@0perator/operator 0.1.172 → 0.1.235
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/CHANGELOG.md +858 -0
- package/README.md +4 -4
- package/dist/acp/agent.js +42 -3
- package/dist/acp/config-options.js +34 -0
- package/dist/acp/run.js +83 -2
- package/dist/auth/byo.js +118 -0
- package/dist/auth/commands.js +34 -1
- package/dist/autonomy/dream.js +1 -1
- package/dist/autonomy/index.js +16 -2
- package/dist/autonomy/media-robot.js +138 -0
- package/dist/autonomy/profile.js +77 -0
- package/dist/autonomy/session-factory.js +13 -9
- package/dist/background/index.js +8 -1
- package/dist/cli.js +132 -95
- package/dist/compose/client.js +56 -0
- package/dist/config/persona.js +186 -14
- package/dist/config/settings.js +49 -16
- package/dist/consolidation/scheduler.js +7 -4
- package/dist/consolidation/sleep.js +15 -1
- package/dist/engine/agent.js +152 -9
- package/dist/engine/aurora.js +73 -14
- package/dist/engine/compaction.js +129 -2
- package/dist/engine/computer-event.js +139 -0
- package/dist/engine/continuation.js +55 -0
- package/dist/engine/contract.js +3 -1
- package/dist/engine/grandmaster.js +13 -3
- package/dist/engine/messages.js +2 -2
- package/dist/engine/redact.js +25 -0
- package/dist/engine/rolling-summary.js +22 -7
- package/dist/engine/router-adapter.js +2 -0
- package/dist/engine/unrestricted.js +51 -0
- package/dist/engine/verify-gate.js +6 -0
- package/dist/index.browser.js +4 -0
- package/dist/index.js +4 -0
- package/dist/memory/index.js +0 -0
- package/dist/permissions/audit.js +4 -1
- package/dist/permissions/policy.js +4 -3
- package/dist/permissions/tier.js +31 -14
- package/dist/remote/host.js +9 -2
- package/dist/router/models.js +43 -2
- package/dist/session.js +113 -36
- package/dist/telemetry/events.js +8 -3
- package/dist/tools/computer.js +1 -1
- package/dist/tools/executor.js +22 -17
- package/dist/tools/mutating.js +6 -0
- package/dist/tools/registry.js +872 -27
- package/dist/tools/shell-session.js +36 -1
- package/dist/tools/tool-output-spill.js +2 -2
- package/dist/ui/ActivitySpinner.js +17 -6
- package/dist/ui/App.js +36 -14
- package/dist/ui/ArtifactPicker.js +109 -0
- package/dist/ui/BusTray.js +70 -0
- package/dist/ui/Composer.js +39 -8
- package/dist/ui/Markdown.js +5 -3
- package/dist/ui/MouseProvider.js +99 -19
- package/dist/ui/QuestionPrompt.js +24 -3
- package/dist/ui/ThinkingSpinner.js +9 -5
- package/dist/ui/ToolStep.js +17 -12
- package/dist/ui/Transcript.js +14 -7
- package/dist/ui/capabilities.js +0 -9
- package/dist/ui/listhit.js +23 -0
- package/dist/ui/mouse.js +22 -0
- package/dist/ui/osc.js +7 -4
- package/dist/ui/progressbar.js +46 -0
- package/dist/ui/shimmer.js +43 -0
- package/dist/ui/theme.js +2 -0
- package/dist/ui/tick.js +48 -0
- package/dist/ui/toolicons.js +69 -0
- package/dist/util/slash.js +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Profile-bound headless sessions — the engine seam for Bot Mode (GW-OHV3-A / Hermes-parity gap #1).
|
|
2
|
+
// A "bot" the messaging gateway runs (one per Telegram/Discord/Slack identity) is nothing more than a
|
|
3
|
+
// long-lived headless Session with its OWN model, persona, memory, and working dir — i.e. a $KODE_PROFILE.
|
|
4
|
+
// This module turns a ProfileConfig into such a Session by DERIVING settings and composing the existing
|
|
5
|
+
// createAutonomySession factory; it does not fork or modify the engine loop. The gateway owns the fan-out
|
|
6
|
+
// (N bots = N sessions) and drives each with session.send(inboundMessage) per chat turn.
|
|
7
|
+
//
|
|
8
|
+
// Why a Session per bot (not a fresh runHeadless per message): a Session carries the conversation + the
|
|
9
|
+
// recalled memory across turns, so a bot actually remembers the chat. runHeadless is one-shot; a bot is a
|
|
10
|
+
// standing conversation. The Session satisfies Worker (send/interrupt/shutdown), which is all the gateway
|
|
11
|
+
// needs.
|
|
12
|
+
//
|
|
13
|
+
// Isolation is the load-bearing part: each profile gets its OWN memory file and rolling-summary path under
|
|
14
|
+
// its home dir. The engine's default memory/summary files are LIVE PRODUCT STATE (the owner's own Operator
|
|
15
|
+
// memory) — a bot writing there would poison the owner's recall and leak one bot's context into another.
|
|
16
|
+
// So a profile NEVER shares those; deriveProfilePaths() sends each bot to ~/.axe/operator/profiles/<id>/.
|
|
17
|
+
import { createAutonomySession } from "./session-factory.js";
|
|
18
|
+
import { MemoryStore } from "../memory/index.js";
|
|
19
|
+
/** A gated, approver-less policy: safe/read tools run, every mutating tool asks → denies. The fail-safe
|
|
20
|
+
* default for a public bot, mirroring dreamPermissions()'s read-mostly posture. */
|
|
21
|
+
function defaultBotPermissions(base) {
|
|
22
|
+
return { mode: "gated", tier: base.permissions.tier };
|
|
23
|
+
}
|
|
24
|
+
/** Resolve a profile's isolated home + the memory/summary files under it. Pure (no I/O) so it's testable;
|
|
25
|
+
* the MemoryStore + the engine create the files lazily on first write. */
|
|
26
|
+
export function deriveProfilePaths(profile, home = defaultHome()) {
|
|
27
|
+
const root = profile.home ?? `${home}/profiles/${profile.id}`;
|
|
28
|
+
return { home: root, memoryFile: `${root}/Operator_Memory.jsonl`, summaryFile: `${root}/summary.md` };
|
|
29
|
+
}
|
|
30
|
+
/** ~/.axe/operator — the Operator home that the default memory file lives under. Resolved lazily (env/HOME
|
|
31
|
+
* at call time), matching memory/index.ts's defaultFile(). */
|
|
32
|
+
function defaultHome() {
|
|
33
|
+
return process.env.KODE_HOME ?? `${process.env.HOME ?? ""}/.axe/operator`;
|
|
34
|
+
}
|
|
35
|
+
/** Derive this bot's OperatorSettings from the base: swap the served model/endpoint, persona, recall. The
|
|
36
|
+
* base is never mutated (shallow clone of the touched branches), so N profiles derive from one base safely. */
|
|
37
|
+
export function deriveProfileSettings(base, profile) {
|
|
38
|
+
const endpoints = {
|
|
39
|
+
...base.endpoints,
|
|
40
|
+
aurora: {
|
|
41
|
+
...base.endpoints.aurora,
|
|
42
|
+
...(profile.model ? { model: profile.model } : {}),
|
|
43
|
+
...(profile.modelBase ? { base: profile.modelBase } : {}),
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
...base,
|
|
48
|
+
endpoints,
|
|
49
|
+
...(profile.model ? { activeModel: profile.model } : {}),
|
|
50
|
+
...(profile.persona !== undefined ? { systemPrompt: profile.persona } : {}),
|
|
51
|
+
...(profile.recall !== undefined ? { memory: { ...base.memory, recall: profile.recall } } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Build a long-lived, memory-isolated Session for one bot. The gateway calls this ONCE per configured bot,
|
|
56
|
+
* then drives it with session.send(inboundMessage, handlers) per chat turn — the Session keeps the
|
|
57
|
+
* conversation + recalled memory across turns, so the bot remembers. session.interrupt() cancels the
|
|
58
|
+
* in-flight turn; session.shutdown() tears it down.
|
|
59
|
+
*
|
|
60
|
+
* Model / persona / permissions come from the profile; memory + rolling summary are isolated to the bot's
|
|
61
|
+
* home dir so no bot ever touches the owner's live Operator memory. A ComputerEvent feed (for a "bot is
|
|
62
|
+
* working" indicator) is opt-in: pass through opts.extra.onComputerEvent / computerEnv — unset by default.
|
|
63
|
+
*/
|
|
64
|
+
export function createProfileSession(base, profile, opts = {}) {
|
|
65
|
+
const paths = deriveProfilePaths(profile);
|
|
66
|
+
const settings = deriveProfileSettings(base, profile);
|
|
67
|
+
return createAutonomySession(settings, {
|
|
68
|
+
permissions: opts.permissions ?? profile.permissions ?? defaultBotPermissions(base),
|
|
69
|
+
extra: {
|
|
70
|
+
sessionId: `profile:${profile.id}`,
|
|
71
|
+
cwd: profile.cwd ?? paths.home,
|
|
72
|
+
memory: new MemoryStore(paths.memoryFile),
|
|
73
|
+
rollingSummaryPath: paths.summaryFile,
|
|
74
|
+
...opts.extra, // a caller (tests, or a host wanting onComputerEvent) can still override/extend
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
// way the shell does. Kept deliberately small: it composes existing building blocks, it does not fork them.
|
|
5
5
|
import { Session } from "../session.js";
|
|
6
6
|
import { AuroraRouter } from "../router/router.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { compactionThreshold, compactionCeilingTokens } from "../config/settings.js";
|
|
7
|
+
import { composeSystemPrompt } from "../config/persona.js";
|
|
8
|
+
import { modelCtxFor, LEAN_HARNESS_CTX } from "../router/models.js";
|
|
9
|
+
import { compactionThreshold, compactionCeilingTokens, turnWallClockMs } from "../config/settings.js";
|
|
10
10
|
/** Build the Aurora router (primary + optional degraded failover) from settings — the headless twin of
|
|
11
11
|
* cli.tsx's buildRouter(). */
|
|
12
12
|
export function buildRouterFromSettings(settings) {
|
|
@@ -21,11 +21,12 @@ export function buildRouterFromSettings(settings) {
|
|
|
21
21
|
eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
|
|
22
22
|
return new AuroraRouter(eps);
|
|
23
23
|
}
|
|
24
|
-
/** The full headless system prompt:
|
|
25
|
-
*
|
|
24
|
+
/** The full headless system prompt: the SAME composeSystemPrompt the TUI calls (persona + project context +
|
|
25
|
+
* memory + handoff + catalogue), non-interactive — minus the TUI-only Sub-agents + embodiment sections. */
|
|
26
26
|
export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
|
|
27
|
-
const
|
|
28
|
-
|
|
27
|
+
const ctxTokens = modelCtxFor(settings.activeModel, settings.models);
|
|
28
|
+
const lean = ctxTokens < LEAN_HARNESS_CTX; // small-ctx model → drop heavy memory/handoff (persona kept → stays uncensored)
|
|
29
|
+
return composeSystemPrompt({ settings, cwd, ctxTokens, lean, interactive: false });
|
|
29
30
|
}
|
|
30
31
|
/** Construct a headless Session from settings. Unattended runs get NO ask_user handler (there's no owner
|
|
31
32
|
* to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
|
|
@@ -36,7 +37,9 @@ export function createAutonomySession(settings, opts = {}) {
|
|
|
36
37
|
router: buildRouterFromSettings(settings),
|
|
37
38
|
mcp: settings.mcp,
|
|
38
39
|
maxTokens: settings.maxTokens,
|
|
39
|
-
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling
|
|
40
|
+
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling; default unset ⇒ unattended runs are uncapped (free reign)
|
|
41
|
+
maxTurnWallClockMs: turnWallClockMs(settings), // per-turn TIME brake (default 15min) — stops the hour-long crawling turn; loop mode continues the objective next turn
|
|
42
|
+
maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a deep unattended build runs to completion before the wrap-up nudge; was never passed here, so headless runs fell back to the engine's 10-round floor and cut long missions short
|
|
40
43
|
temperature: settings.temperature,
|
|
41
44
|
recall: settings.memory.recall,
|
|
42
45
|
models: settings.models,
|
|
@@ -45,7 +48,8 @@ export function createAutonomySession(settings, opts = {}) {
|
|
|
45
48
|
permissions: opts.permissions ?? settings.permissions,
|
|
46
49
|
telemetry: settings.telemetry,
|
|
47
50
|
compactionThreshold: compactionThreshold(settings),
|
|
48
|
-
compactionCeilingTokens: compactionCeilingTokens(settings),
|
|
51
|
+
compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow, "autonomy"), // AUTONOMY mode ⇒ the high headless ceiling (~100k, just under the swap cliff), independent of the tight interactive ceilingTokens — so a snappy interactive setting can't throttle an unattended build into a compaction-thrash loop
|
|
52
|
+
sleepConsolidation: settings.autonomy?.sleepConsolidation, // headless autonomy ("operator run/loop/dream") consolidates on idle too (0.1.177)
|
|
49
53
|
...opts.extra,
|
|
50
54
|
});
|
|
51
55
|
}
|
package/dist/background/index.js
CHANGED
|
@@ -187,6 +187,13 @@ export class BackgroundAgents {
|
|
|
187
187
|
// Isolation: a file-editing child gets its own git worktree so it can't touch the foreground tree; its
|
|
188
188
|
// Session's tools are rooted there (Executor cwd). Read-only lanes (search/review/plan) share the live
|
|
189
189
|
// cwd — they SHOULD see the real tree, and a snapshot copy would be stale. Best-effort: no repo → no wt.
|
|
190
|
+
// Capture diffSha BEFORE the worktree — the HEAD at the point the task was spawned (the "before" state).
|
|
191
|
+
let diffSha;
|
|
192
|
+
try {
|
|
193
|
+
const { execSync } = await import("node:child_process");
|
|
194
|
+
diffSha = execSync("git rev-parse HEAD", { cwd: process.cwd(), encoding: "utf8", stdio: "pipe" }).trim();
|
|
195
|
+
}
|
|
196
|
+
catch { /* not a git repo — mutation check will be skipped */ }
|
|
190
197
|
const wt = (type === "code-edit" && process.env.KODE_BG_WORKTREE !== "0") ? await createWorktree(id, process.cwd()) : null;
|
|
191
198
|
const cwd = wt?.dir;
|
|
192
199
|
let session;
|
|
@@ -295,7 +302,7 @@ export class BackgroundAgents {
|
|
|
295
302
|
// Mechanism 3: verify-before-done (never on the model's say-so). Verify runs IN the worktree, so a
|
|
296
303
|
// code-editing child's declared verify_command tests the files it actually changed (in isolation).
|
|
297
304
|
if (fa.ok && fa.value) {
|
|
298
|
-
const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd());
|
|
305
|
+
const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd(), { diffSha });
|
|
299
306
|
info.verified = v.verified;
|
|
300
307
|
info.verifyDetail = v.detail;
|
|
301
308
|
}
|
package/dist/cli.js
CHANGED
|
@@ -8,7 +8,6 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
|
|
8
8
|
import { render, Box, Text, useApp } from "ink";
|
|
9
9
|
import { App } from "./ui/index.js";
|
|
10
10
|
import { mastheadLines } from "./ui/Masthead.js";
|
|
11
|
-
import { hyperlinkHint } from "./ui/capabilities.js";
|
|
12
11
|
import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
|
|
13
12
|
import { RemoteHost } from "./remote/host.js";
|
|
14
13
|
import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
|
|
@@ -20,14 +19,17 @@ import { seedCalibration } from "./engine/calibration-seed.js";
|
|
|
20
19
|
import { AuroraRouter } from "./router/router.js";
|
|
21
20
|
import { BackgroundAgents } from "./background/index.js";
|
|
22
21
|
import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart } from "./config/settings.js";
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
22
|
+
import { caps } from "./ui/capabilities.js";
|
|
23
|
+
import { composeSystemPrompt, appendMemory } from "./config/persona.js";
|
|
24
|
+
import { modelCtxFor, LEAN_HARNESS_CTX } from "./router/models.js";
|
|
25
25
|
import { disposeShellSession, getAgentTasks } from "./tools/registry.js";
|
|
26
26
|
import { EventSink } from "./telemetry/events.js";
|
|
27
27
|
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
28
28
|
import { expandFileMentions } from "./util/mentions.js";
|
|
29
29
|
import { throttle } from "./util/throttle.js";
|
|
30
30
|
import { isSlashCommand } from "./util/slash.js";
|
|
31
|
+
import * as compose from "./compose/client.js";
|
|
32
|
+
import { execFile } from "node:child_process";
|
|
31
33
|
import { join, dirname } from "node:path";
|
|
32
34
|
import { homedir, hostname } from "node:os";
|
|
33
35
|
import { createHash } from "node:crypto";
|
|
@@ -152,7 +154,7 @@ const SESSION_DIR = join(homedir(), ".axe", "operator", "sessions");
|
|
|
152
154
|
const SESSION_FILE = process.env.KODE_SESSION_FILE ??
|
|
153
155
|
join(SESSION_DIR, `${createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16)}.json`);
|
|
154
156
|
try {
|
|
155
|
-
mkdirSync(SESSION_DIR, { recursive: true });
|
|
157
|
+
mkdirSync(SESSION_DIR, { recursive: true, mode: 0o700 });
|
|
156
158
|
}
|
|
157
159
|
catch { /* best-effort; the write is guarded too */ }
|
|
158
160
|
const RESUME = process.argv.includes("--resume") || process.argv.includes("-r") || process.env.KODE_RESUME === "1";
|
|
@@ -215,90 +217,30 @@ function formatAgentDetail(a) {
|
|
|
215
217
|
parts.push("— errored");
|
|
216
218
|
return parts.join(" ");
|
|
217
219
|
}
|
|
218
|
-
//
|
|
219
|
-
// autonomy runners (autonomy/session-factory.ts) so an unattended `operator run/loop`
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
// failed on Slack (AppleScript can't read Electron UIs). chauffeur is reachable either via the scoped
|
|
224
|
-
// embodiment hub or the full fleet MCP.
|
|
220
|
+
// The system prompt is assembled by config/persona.ts composeSystemPrompt — the SAME call the headless
|
|
221
|
+
// autonomy runners (autonomy/session-factory.ts) make — so the TUI and an unattended `operator run/loop`
|
|
222
|
+
// share one persona (Direct/unrestricted, media, verify-by-running) + project context + handoff.
|
|
223
|
+
// chauffeur (textual on-screen UI reads) is reachable via the scoped embodiment hub or the full fleet MCP —
|
|
224
|
+
// the gate for the embodiment guide composeSystemPrompt appends when computer control is on.
|
|
225
225
|
const chauffeurReady = !!chauffeurServer || settings.mcp;
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
`never answer from memory and never say you cannot see the screen. First call: chauffeur:list_windows. ` +
|
|
234
|
-
`Correct usage, follow it exactly:\n` +
|
|
235
|
-
`- Do NOT pass a "session" argument to any chauffeur tool. Omit it — the implicit session is used ` +
|
|
236
|
-
`automatically. (Inventing a session label causes "session has ended" errors.)\n` +
|
|
237
|
-
`- At the START of any on-screen task, call chauffeur:set_agent_cursor_enabled {enabled: true} so the ` +
|
|
238
|
-
`owner can watch the agent's cursor move — do this before the first click/type/drag.\n` +
|
|
239
|
-
`- To read a window: call chauffeur:list_windows, take a window_id + pid FROM THAT RESULT, then ` +
|
|
240
|
-
`immediately chauffeur:get_window_state {pid, window_id} → a TEXT accessibility tree (roles, labels, ` +
|
|
241
|
-
`values, clickable elements + coordinates). window_ids go stale, so always list_windows again right ` +
|
|
242
|
-
`before get_window_state; never reuse an old id.\n` +
|
|
243
|
-
`- To act: chauffeur:click / chauffeur:type_text / chauffeur:press_key, addressing elements by the info ` +
|
|
244
|
-
`from the latest get_window_state.\n` +
|
|
245
|
-
`- If ANY chauffeur tool returns "session has ended", call chauffeur:start_session ONCE (no arguments), ` +
|
|
246
|
-
`then retry the read — do not loop the failing call.\n` +
|
|
247
|
-
`Work END-TO-END from the owner's one instruction: read → decide → act by chaining these tools yourself, ` +
|
|
248
|
-
`then report the result. Reads run without a prompt; only actions ask. Use ask_user only for a genuine ` +
|
|
249
|
-
`owner decision — never to walk through a task you can just do.`
|
|
250
|
-
: ` NOTE: reliably READING on-screen UI (especially Electron apps like Slack) needs the chauffeur driver, ` +
|
|
251
|
-
`which is not installed here; computer_screenshot only saves a PNG you cannot read back yet. Do not ` +
|
|
252
|
-
`hand-write osascript to scrape a GUI — it will error on Electron apps.`)
|
|
253
|
-
: "";
|
|
254
|
-
const SYSTEM_PROMPT = (settings.systemPrompt ??
|
|
255
|
-
`You are Operator, AXE's terminal coding agent — built by AXE, running on AXE's own model. Refer to ` +
|
|
256
|
-
`yourself as Operator and to the platform as AXE; never call yourself or the platform Claude, ` +
|
|
257
|
-
`Anthropic, or any other vendor. When you encounter files or directories on disk named "claude", ` +
|
|
258
|
-
`".claude", "anthropic", etc., describe them neutrally (by their literal path, or as "AI tooling ` +
|
|
259
|
-
`files") — do not attribute them to a vendor. Use your tools to inspect and edit the ` +
|
|
260
|
-
`workspace; prefer doing over explaining. Answer concisely.\n## This machine\nWorking dir: ${process.cwd()}` +
|
|
261
|
-
`\nContext window: 307,200 tokens (300K) — you run on AXE's model served locally with a real 300K-token ` +
|
|
262
|
-
`context. You can hold large files and long histories; do not claim a different limit.` +
|
|
263
|
-
`\n## Parallel tool calls\nWhen the next few steps are INDEPENDENT of each other — reading several ` +
|
|
264
|
-
`files, running several greps/checks, inspecting multiple unrelated things — issue them as multiple ` +
|
|
265
|
-
`tool calls in a SINGLE message so they run in parallel, instead of one call, waiting, then the next. ` +
|
|
266
|
-
`Only serialize when one call's output feeds the next call's input (e.g. read a file, then edit it), ` +
|
|
267
|
-
`or when a call mutates something the next call depends on seeing. Batching independent reads is ` +
|
|
268
|
-
`almost always faster and is the default you should reach for; do not artificially serialize work ` +
|
|
269
|
-
`that has no real dependency.` +
|
|
270
|
-
`\n## Sub-agents\nFor independent, parallelizable subtasks (search a large tree, draft a file, a long ` +
|
|
271
|
-
`build) call spawn_agent with a fully self-contained instruction — it runs on another session ` +
|
|
272
|
-
`in parallel and posts its result back here; keep working meanwhile. The user watches each sub-agent's ` +
|
|
273
|
-
`live tokens + time in the background panel. Don't delegate trivial work you can do inline, and don't ` +
|
|
274
|
-
`spawn many at once — they all share this one model.` +
|
|
275
|
-
`\n## Finding things\nTo search file CONTENTS (a symbol, a string, a config key), use the search tool ` +
|
|
276
|
-
`(ripgrep — fast, parallel, .gitignore-aware) scoped to a directory: search {"pattern":"…","path":"src"}, ` +
|
|
277
|
-
`and set files_with_matches to just locate the files before reading them. NEVER run ` +
|
|
278
|
-
`\`find ~/ -maxdepth N | grep | grep\` over the whole home directory — it is slow, hits the command ` +
|
|
279
|
-
`timeout, and can wedge the shell. Narrow FIRST: check the 2-3 most likely directories before any broad ` +
|
|
280
|
-
`sweep, and batch independent searches in ONE message so they run in parallel.\nWhen asked to find a ` +
|
|
281
|
-
`project or file by NAME that is NOT in the working directory: (1) run ls ~ to see the REAL top-level ` +
|
|
282
|
-
`folders (projects live in non-obvious ones — e.g. ~/Axwell, ~/.axe/repos, ~/Desktop — not just ` +
|
|
283
|
-
`~/Projects); (2) then a BOUNDED find scoped to a SPECIFIC directory with a generous timeout — ` +
|
|
284
|
-
`shell_exec {"command":"find ~/.axe/repos -maxdepth 3 -iname \\"*name*\\" 2>/dev/null | head -80",` +
|
|
285
|
-
`"timeout_ms":60000} — never an unbounded find over all of ~ or /. Widen the pattern if a repo may be ` +
|
|
286
|
-
`named differently. Only report not-found after this real search, and say exactly where you looked.` +
|
|
287
|
-
`\n## Scratchpad & handoff\nUse the scratchpad tool for private working notes, plans, and intermediate ` +
|
|
288
|
-
`results — think there, not in the workspace or your reply. Before you finish a substantial task, or ` +
|
|
289
|
-
`when you're running low on context, call session_handoff to record what you did, the state, and the ` +
|
|
290
|
-
`next steps: your next session in this directory loads it automatically, so write it for your future self.`) +
|
|
291
|
-
loadProjectContext() + loadMemories() + renderHarnessContext() + loadHandoff() + EMBODIMENT_GUIDE;
|
|
226
|
+
// Small-context models (e.g. a self-hosted 8K Venice) can't hold Operator's full memory + handoff — sized
|
|
227
|
+
// for Aurora's 300K, it fills the window and the model recites it instead of answering. Below
|
|
228
|
+
// LEAN_HARNESS_CTX, drop the heavy memory/handoff, KEEPING the base persona (incl. the Direct/unrestricted
|
|
229
|
+
// section) so the model stays uncensored.
|
|
230
|
+
const LEAN_HARNESS = modelCtxFor(settings.activeModel, settings.models) < LEAN_HARNESS_CTX;
|
|
231
|
+
// TODO(R1b): built once at startup — a mid-session /model does not rebuild it (ctxTokens + lean follow the startup model).
|
|
232
|
+
const SYSTEM_PROMPT = composeSystemPrompt({ settings, cwd: process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), lean: LEAN_HARNESS, interactive: true, chauffeurReady });
|
|
292
233
|
const HELP = [
|
|
293
234
|
"commands:",
|
|
294
235
|
" /help this list",
|
|
295
|
-
" /model [id] pick a model: operator-1m · operator-128k ·
|
|
236
|
+
" /model [id] pick a model: operator-1m · operator-128k · qwen connectors (auth byo qwen) · moa",
|
|
296
237
|
" /endpoints show the Operator endpoint + live health",
|
|
297
238
|
" /services ensure/inspect the service lever (Operator+autopilot+searxng); /services stop",
|
|
298
239
|
" /audit [n] recent tool + control-plane events from the audit trail (default 15)",
|
|
299
240
|
" /monitor live event stream — tool decisions, turns, control events (/monitor off)",
|
|
300
241
|
" /stats session dashboard: turns · tools · tokens · throughput trend · context fill",
|
|
301
242
|
" /dashboard launch the live swarm console (watches every Operator session)",
|
|
243
|
+
" /artifacts browse + attach your Compose (compose.casa) artifacts: search · attach · copy url · delete",
|
|
302
244
|
" /plan plan mode: read-only research + propose a plan (/plan again to execute)",
|
|
303
245
|
" /mode [plan|manual|auto] set operating mode (plan · manual · autonomous); also Shift+Tab to cycle",
|
|
304
246
|
" /think extended reasoning: Operator thinks before answering (/think again = off)",
|
|
@@ -306,7 +248,7 @@ const HELP = [
|
|
|
306
248
|
" /compact force-compact the conversation now",
|
|
307
249
|
" /remember <note> store a note to recall in future sessions",
|
|
308
250
|
" /memory [query] show remembered notes (all, or matching query)",
|
|
309
|
-
" /mcp
|
|
251
|
+
" /mcp [on|off] fleet MCP tools: status, or switch the layer on/off (saved)",
|
|
310
252
|
" /login <email> · /logout · /whoami sign in by 6-digit email code (then /login <code>); /login <token> or --browser",
|
|
311
253
|
" /agents detailed sub-agent status: running/queued/done/errored + metrics",
|
|
312
254
|
" /bg <task|stop id> spawn a background sub-agent, list, or stop one",
|
|
@@ -339,7 +281,7 @@ const REMOTE_SAFE_COMMANDS = [
|
|
|
339
281
|
{ name: "compact", description: "force-compact the conversation now" },
|
|
340
282
|
{ name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
|
|
341
283
|
{ name: "memory", description: "show remembered notes", args: "[query]" },
|
|
342
|
-
{ name: "mcp", description: "
|
|
284
|
+
{ name: "mcp", description: "fleet MCP tools: status · switch the layer on/off", args: "[on|off]" },
|
|
343
285
|
{ name: "whoami", description: "show signed-in identity" },
|
|
344
286
|
{ name: "agents", description: "detailed sub-agent status with metrics" },
|
|
345
287
|
{ name: "monitor", description: "toggle live event stream (tool decisions, turns, control)" },
|
|
@@ -385,7 +327,7 @@ function Root() {
|
|
|
385
327
|
// Ref mirror of opMode so buildCapabilities() reflects the LIVE mode synchronously (a follower's mode
|
|
386
328
|
// selector must light up the instant it changes, before React flushes the setOpMode state update).
|
|
387
329
|
const opModeRef = useRef(opMode);
|
|
388
|
-
const [thinkMode, setThinkMode] = useState("
|
|
330
|
+
const [thinkMode, setThinkMode] = useState(settings.ui?.reasoning ?? "think"); // /think, /ultrathink badge; default "think" so the model's thoughts stream dim above the answer (settings.ui.reasoning / /think to change)
|
|
389
331
|
const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
|
|
390
332
|
const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
|
|
391
333
|
// phase where no content tokens stream — that was the "timer stuck" bug (Ink only re-renders on deltas).
|
|
@@ -420,6 +362,7 @@ function Root() {
|
|
|
420
362
|
// Gates the exit-time picker below — plan mode toggled on/off with no proposal stays silent.
|
|
421
363
|
const planProposedRef = useRef(false);
|
|
422
364
|
const [planExitPicker, setPlanExitPicker] = useState(null);
|
|
365
|
+
const [artifactsPicker, setArtifactsPicker] = useState(null);
|
|
423
366
|
const alwaysAllowRef = useRef(new Set());
|
|
424
367
|
// Remembers the email a `/login <email>` sent a 6-digit code to, so the follow-up `/login <code>`
|
|
425
368
|
// knows which address to verify against — the in-session twin of the shell's email-code login.
|
|
@@ -458,14 +401,16 @@ function Root() {
|
|
|
458
401
|
if (!sessionRef.current) {
|
|
459
402
|
sessionRef.current = new Session({
|
|
460
403
|
systemPrompt: SYSTEM_PROMPT,
|
|
404
|
+
thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
|
|
461
405
|
router: buildRouter(),
|
|
462
406
|
mcp: settings.mcp,
|
|
463
407
|
mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
|
|
464
408
|
maxTokens: settings.maxTokens,
|
|
465
409
|
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
|
|
466
|
-
maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default
|
|
410
|
+
maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a real build isn't cut off at 10
|
|
411
|
+
sleepConsolidation: settings.autonomy?.sleepConsolidation, // idle "dreaming": consolidate transcript→memory + run the flywheel while the owner is away (0.1.177 — was never threaded through, so it never fired)
|
|
467
412
|
compactionThreshold: compactionThreshold(settings), // settings.compaction.threshold / KODE_COMPACTION_THRESHOLD; undefined → 0.85
|
|
468
|
-
compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow), //
|
|
413
|
+
compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow, "interactive"), // INTERACTIVE mode ⇒ the tight ceiling (~24k) so each owner-facing reply decodes fast; compaction.ceilingTokens/env override, then the RAM-aware clamp. Headless autonomy uses the separate high ceiling (session-factory.ts)
|
|
469
414
|
temperature: settings.temperature,
|
|
470
415
|
recall: settings.memory.recall,
|
|
471
416
|
models: settings.models, // /model registry overrides (router/models.ts has the built-in defaults)
|
|
@@ -737,7 +682,7 @@ function Root() {
|
|
|
737
682
|
onRoute: (label, pct) => {
|
|
738
683
|
setRoute(label);
|
|
739
684
|
setCtxPct(pct);
|
|
740
|
-
remoteRef.current?.setStatus(pct, label);
|
|
685
|
+
remoteRef.current?.setStatus(pct, label, session.sessionTokens());
|
|
741
686
|
// GW-06 oracle seed (once, fire-and-forget): a fresh meter cold-starts at chars/4 (4.0) — measured
|
|
742
687
|
// truth on agent traffic is ~2.15 (aurora-tier0/calibrate-token-meter.py), i.e. the gate fires LATE
|
|
743
688
|
// for the first rounds. Seed ONE weight-1 observation from the endpoint's own tokenizer
|
|
@@ -798,6 +743,13 @@ function Root() {
|
|
|
798
743
|
// tool box) that Ink can mis-erase, stamping the same "let me check…" line once per tool — the
|
|
799
744
|
// redundancy. The prose already showed while it streamed; during execution we show the tool rows,
|
|
800
745
|
// not a re-rendered copy of it. (onToolBatch also clears these once the batch fully settles.)
|
|
746
|
+
// BUT the model's THINKING before this batch ("why I'm running these tools") is worth keeping — so
|
|
747
|
+
// persist it as a dim, SETTLED thought ABOVE the tool rows before clearing. Settled entries render
|
|
748
|
+
// once into static scrollback (no live re-render), so this dodges the tall-live-frame mis-erase the
|
|
749
|
+
// clear guards against while surfacing the inter-batch reasoning the owner would otherwise lose.
|
|
750
|
+
const preThought = liveReasoning.current.trim();
|
|
751
|
+
if (preThought)
|
|
752
|
+
push({ kind: "message", message: { id: nextId(), role: "assistant", content: "", reasoning: preThought } });
|
|
801
753
|
liveText.current = "";
|
|
802
754
|
liveReasoning.current = "";
|
|
803
755
|
setLive(null);
|
|
@@ -909,8 +861,9 @@ function Root() {
|
|
|
909
861
|
const live = bg.list().filter((a) => a.status === "working" || a.status === "queued");
|
|
910
862
|
if (live.length)
|
|
911
863
|
push({ kind: "message", message: { id: nextId(), role: "system", content: `${live.length} sub-agent${live.length > 1 ? "s" : ""} still running — results post when done. /agents for status` } });
|
|
864
|
+
// H4 (audit-tools §1): transcripts hold bearer tokens — they were world-readable by default.
|
|
912
865
|
try {
|
|
913
|
-
writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()));
|
|
866
|
+
writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()), { mode: 0o600 });
|
|
914
867
|
}
|
|
915
868
|
catch { /* auto-save is best-effort */ }
|
|
916
869
|
// Re-check capabilities after every turn: MCP discovery (first-turn only) may have just landed,
|
|
@@ -1040,6 +993,69 @@ function Root() {
|
|
|
1040
993
|
});
|
|
1041
994
|
break;
|
|
1042
995
|
}
|
|
996
|
+
case "artifacts": {
|
|
997
|
+
// Browse + attach Compose (compose.casa) artifacts. Fetches the owner's library over Operator's
|
|
998
|
+
// existing AuthGate token (src/compose/client.ts — the scoped HTTP API, never the unauth MCP),
|
|
999
|
+
// renders the ArtifactPicker, and maps each row action to a Compose call. Attach fetches the
|
|
1000
|
+
// content and re-enters it as a framed user turn (the proven submitRef inject path) so the model
|
|
1001
|
+
// can use it. rename/pin/Shared are Phase 2/3 (need Compose backend work) — see the _ai-docs spec.
|
|
1002
|
+
const setPatch = (patch) => setArtifactsPicker((p) => (p ? { ...p, ...patch } : p));
|
|
1003
|
+
const load = async (fetcher) => {
|
|
1004
|
+
setPatch({ loading: true, error: undefined, note: undefined });
|
|
1005
|
+
try {
|
|
1006
|
+
setPatch({ items: await fetcher(), loading: false });
|
|
1007
|
+
}
|
|
1008
|
+
catch (e) {
|
|
1009
|
+
setPatch({ loading: false, error: e.message });
|
|
1010
|
+
}
|
|
1011
|
+
};
|
|
1012
|
+
const onIntent = async (intent) => {
|
|
1013
|
+
switch (intent.kind) {
|
|
1014
|
+
case "close":
|
|
1015
|
+
setArtifactsPicker(null);
|
|
1016
|
+
break;
|
|
1017
|
+
case "refresh":
|
|
1018
|
+
await load(() => compose.listMine());
|
|
1019
|
+
break;
|
|
1020
|
+
case "search":
|
|
1021
|
+
await load(() => (intent.query ? compose.search(intent.query) : compose.listMine()));
|
|
1022
|
+
break;
|
|
1023
|
+
case "copy": {
|
|
1024
|
+
const url = compose.viewUrl(intent.id);
|
|
1025
|
+
try {
|
|
1026
|
+
const c = execFile(process.platform === "darwin" ? "pbcopy" : process.platform === "win32" ? "clip" : "xclip");
|
|
1027
|
+
c.stdin?.end(url);
|
|
1028
|
+
}
|
|
1029
|
+
catch { /* best-effort; the url is shown below regardless */ }
|
|
1030
|
+
setPatch({ note: `copied ${url}` });
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
case "delete":
|
|
1034
|
+
try {
|
|
1035
|
+
await compose.del(intent.id);
|
|
1036
|
+
setPatch({ note: "deleted" });
|
|
1037
|
+
await load(() => compose.listMine());
|
|
1038
|
+
}
|
|
1039
|
+
catch (e) {
|
|
1040
|
+
setPatch({ error: e.message });
|
|
1041
|
+
}
|
|
1042
|
+
break;
|
|
1043
|
+
case "attach":
|
|
1044
|
+
try {
|
|
1045
|
+
const a = await compose.get(intent.id);
|
|
1046
|
+
setArtifactsPicker(null);
|
|
1047
|
+
submitRef.current(`[Attached Compose artifact: ${a.title} — ${compose.viewUrl(a.id)}]\n\n${a.content}`);
|
|
1048
|
+
}
|
|
1049
|
+
catch (e) {
|
|
1050
|
+
setPatch({ error: e.message });
|
|
1051
|
+
}
|
|
1052
|
+
break;
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
setArtifactsPicker({ items: [], loading: true, onIntent });
|
|
1056
|
+
void load(() => compose.listMine());
|
|
1057
|
+
break;
|
|
1058
|
+
}
|
|
1043
1059
|
case "route":
|
|
1044
1060
|
if (s.pinRoute(arg || "auto"))
|
|
1045
1061
|
sys(arg && arg !== "auto" ? `routing pinned to ${arg}` : "routing set to auto (by size)");
|
|
@@ -1211,8 +1227,22 @@ function Root() {
|
|
|
1211
1227
|
break;
|
|
1212
1228
|
}
|
|
1213
1229
|
case "mcp": {
|
|
1214
|
-
const
|
|
1215
|
-
|
|
1230
|
+
const a = (arg ?? "").trim().toLowerCase();
|
|
1231
|
+
if (a === "on") {
|
|
1232
|
+
sys("enabling MCP tools…");
|
|
1233
|
+
const n = await s.enableMcp();
|
|
1234
|
+
saveSettings({ mcp: true });
|
|
1235
|
+
sys(n > 0 ? `MCP on · ${n} fleet tools available (saved — on for new sessions too)` : "MCP on (saved), but no tools were discovered — the MCP gateway may be unreachable; it retries next session");
|
|
1236
|
+
}
|
|
1237
|
+
else if (a === "off") {
|
|
1238
|
+
saveSettings({ mcp: false });
|
|
1239
|
+
sys("MCP off for new sessions (saved) — tools already loaded stay until you restart");
|
|
1240
|
+
}
|
|
1241
|
+
else {
|
|
1242
|
+
const n = s.mcpToolCount();
|
|
1243
|
+
sys(n > 0 ? `${n} fleet MCP tools available this session · /mcp off to disable for new sessions`
|
|
1244
|
+
: settings.mcp ? "MCP is on — tools are discovered when you send your first message" : "no MCP tools loaded — /mcp on to enable them");
|
|
1245
|
+
}
|
|
1216
1246
|
break;
|
|
1217
1247
|
}
|
|
1218
1248
|
case "endpoints": {
|
|
@@ -1561,7 +1591,7 @@ function Root() {
|
|
|
1561
1591
|
? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
|
|
1562
1592
|
: `${spin} ${fmtMeta(elapsed, liveTok)}`
|
|
1563
1593
|
: metrics;
|
|
1564
|
-
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, onApprovalDecide: (allow, always) => {
|
|
1594
|
+
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
|
|
1565
1595
|
const cur = approval;
|
|
1566
1596
|
if (cur)
|
|
1567
1597
|
settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
|
|
@@ -1601,7 +1631,7 @@ if (process.argv[2] === "update" || process.argv.includes("--update")) {
|
|
|
1601
1631
|
// The Ink shell needs a real terminal (raw-mode keyboard). Fail clearly instead of crashing deep
|
|
1602
1632
|
// in useInput when piped/non-interactive — for scripted use, drive Session (src/session.ts) directly.
|
|
1603
1633
|
if (!process.stdin.isTTY) {
|
|
1604
|
-
process.stderr.write("
|
|
1634
|
+
process.stderr.write("Operator needs an interactive terminal (TTY). For a scripted turn, run `operator run \"<task>\"`.\n");
|
|
1605
1635
|
process.exit(1);
|
|
1606
1636
|
}
|
|
1607
1637
|
// Boot masthead (design #29) — printed ONCE to stdout before Ink mounts, so the big gradient wordmark
|
|
@@ -1621,12 +1651,19 @@ if (FULLSCREEN) {
|
|
|
1621
1651
|
}
|
|
1622
1652
|
else {
|
|
1623
1653
|
process.stdout.write(mastheadLines(`300K · v${VERSION}`).join("\n") + "\n");
|
|
1624
|
-
//
|
|
1625
|
-
//
|
|
1626
|
-
//
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1654
|
+
// ONE-TIME ONLY: on a terminal without clickable links / copy-on-select (Terminal.app, or an unknown one),
|
|
1655
|
+
// point the owner at the terminals Operator is built for — then persist the flag so it NEVER shows again.
|
|
1656
|
+
// This is a single first-run pointer, not the per-boot tip that was removed. iTerm2/Ghostty/Kitty/WezTerm
|
|
1657
|
+
// are the standard: OSC 8 links + inline artifacts, and highlight-to-copy work there (Ghostty/iTerm2/WezTerm
|
|
1658
|
+
// do copy-on-select by default; Kitty needs `copy_on_select clipboard`). Terminal.app supports neither.
|
|
1659
|
+
if (!caps().osc8 && !settings.ui?.seenTerminalRecommend) {
|
|
1660
|
+
process.stdout.write("\x1b[2m Operator runs best in iTerm2 · Ghostty · Kitty · WezTerm — clickable links + artifacts and\n" +
|
|
1661
|
+
" highlight-to-copy work there; Terminal.app supports neither. (Shown once.)\x1b[22m\n");
|
|
1662
|
+
try {
|
|
1663
|
+
saveSettings({ ui: { ...settings.ui, seenTerminalRecommend: true } });
|
|
1664
|
+
}
|
|
1665
|
+
catch { /* best-effort; a write failure just re-shows next boot */ }
|
|
1666
|
+
}
|
|
1630
1667
|
}
|
|
1631
1668
|
const inkInstance = render(_jsx(Root, {}));
|
|
1632
1669
|
if (FULLSCREEN)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Compose (compose.casa) HTTP client — the data source for the /artifacts browser. We talk to the
|
|
2
|
+
// properly-scoped HTTP API with Operator's existing AuthGate Bearer token (loadCredentials), NOT the
|
|
3
|
+
// compose MCP: that MCP is mounted unauthenticated and its list/search/delete have no ownership scoping
|
|
4
|
+
// (they act on every artifact in the system), so it is unsafe to build "Mine" on. `/api/mine` is
|
|
5
|
+
// owner-scoped; `/api/list?q=` is the scoped search (NOT `/api/search`, which is global + unscoped).
|
|
6
|
+
// Base is overridable for tests/local via KODE_COMPOSE_URL.
|
|
7
|
+
import { loadCredentials } from "../auth/store.js";
|
|
8
|
+
const BASE = (process.env.KODE_COMPOSE_URL ?? "https://compose.casa").replace(/\/+$/, "");
|
|
9
|
+
export class ComposeError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
constructor(message, status) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.name = "ComposeError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** The public view/share URL for an artifact — a pure string, no network call (the "copy url" action). */
|
|
18
|
+
export function viewUrl(id) {
|
|
19
|
+
return `${BASE}/v/${id}`;
|
|
20
|
+
}
|
|
21
|
+
async function authHeader() {
|
|
22
|
+
const creds = await loadCredentials();
|
|
23
|
+
if (!creds?.token)
|
|
24
|
+
throw new ComposeError("not signed in — run /login to connect to compose.casa", 401);
|
|
25
|
+
return `Bearer ${creds.token}`;
|
|
26
|
+
}
|
|
27
|
+
async function request(method, path) {
|
|
28
|
+
let res;
|
|
29
|
+
try {
|
|
30
|
+
res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: await authHeader(), Accept: "application/json" } });
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
throw new ComposeError(`compose.casa unreachable: ${e.message}`);
|
|
34
|
+
}
|
|
35
|
+
if (!res.ok) {
|
|
36
|
+
const hint = res.status === 401 ? " — token expired? run /login" : "";
|
|
37
|
+
throw new ComposeError(`compose ${method} ${path} → ${res.status}${hint}`, res.status);
|
|
38
|
+
}
|
|
39
|
+
return res;
|
|
40
|
+
}
|
|
41
|
+
/** The owner's library — the real "Mine" tab (AuthGate-scoped). */
|
|
42
|
+
export async function listMine() {
|
|
43
|
+
return (await request("GET", "/api/mine").then((r) => r.json()));
|
|
44
|
+
}
|
|
45
|
+
/** Scoped title+content search (caller's own artifacts), via /api/list?q= — never the global /api/search. */
|
|
46
|
+
export async function search(q) {
|
|
47
|
+
return (await request("GET", `/api/list?q=${encodeURIComponent(q)}`).then((r) => r.json()));
|
|
48
|
+
}
|
|
49
|
+
/** One artifact's content + metadata (the "attach" fetch). */
|
|
50
|
+
export async function get(id) {
|
|
51
|
+
return (await request("GET", `/api/${encodeURIComponent(id)}`).then((r) => r.json()));
|
|
52
|
+
}
|
|
53
|
+
/** Delete one artifact (owner-checked server-side). */
|
|
54
|
+
export async function del(id) {
|
|
55
|
+
await request("DELETE", `/api/${encodeURIComponent(id)}`);
|
|
56
|
+
}
|