agentcut 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +11 -2
- package/dist/bridge.d.ts +45 -0
- package/dist/bridge.js +691 -0
- package/dist/bridge.js.map +1 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.js +50 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +35 -0
- package/dist/index.js.map +1 -0
- package/dist/log.d.ts +1 -0
- package/dist/log.js +14 -0
- package/dist/log.js.map +1 -0
- package/dist/studio/agents/claude.d.ts +7 -0
- package/dist/studio/agents/claude.js +155 -0
- package/dist/studio/agents/claude.js.map +1 -0
- package/dist/studio/agents/codex.d.ts +4 -0
- package/dist/studio/agents/codex.js +169 -0
- package/dist/studio/agents/codex.js.map +1 -0
- package/dist/studio/agents/index.d.ts +8 -0
- package/dist/studio/agents/index.js +50 -0
- package/dist/studio/agents/index.js.map +1 -0
- package/dist/studio/agents/types.d.ts +131 -0
- package/dist/studio/agents/types.js +11 -0
- package/dist/studio/agents/types.js.map +1 -0
- package/dist/studio/bundler.d.ts +29 -0
- package/dist/studio/bundler.js +136 -0
- package/dist/studio/bundler.js.map +1 -0
- package/dist/studio/chat.d.ts +147 -0
- package/dist/studio/chat.js +681 -0
- package/dist/studio/chat.js.map +1 -0
- package/dist/studio/cli.d.ts +2 -0
- package/dist/studio/cli.js +194 -0
- package/dist/studio/cli.js.map +1 -0
- package/dist/studio/components.d.ts +4 -0
- package/dist/studio/components.js +36 -0
- package/dist/studio/components.js.map +1 -0
- package/dist/studio/host.d.ts +105 -0
- package/dist/studio/host.js +634 -0
- package/dist/studio/host.js.map +1 -0
- package/dist/studio/http.d.ts +21 -0
- package/dist/studio/http.js +240 -0
- package/dist/studio/http.js.map +1 -0
- package/dist/studio/music.d.ts +35 -0
- package/dist/studio/music.js +130 -0
- package/dist/studio/music.js.map +1 -0
- package/dist/studio/proc.d.ts +11 -0
- package/dist/studio/proc.js +69 -0
- package/dist/studio/proc.js.map +1 -0
- package/dist/studio/projects.d.ts +84 -0
- package/dist/studio/projects.js +369 -0
- package/dist/studio/projects.js.map +1 -0
- package/dist/studio/render.d.ts +24 -0
- package/dist/studio/render.js +197 -0
- package/dist/studio/render.js.map +1 -0
- package/dist/studio/reveal.d.ts +7 -0
- package/dist/studio/reveal.js +49 -0
- package/dist/studio/reveal.js.map +1 -0
- package/dist/studio/schema.d.ts +4152 -0
- package/dist/studio/schema.js +358 -0
- package/dist/studio/schema.js.map +1 -0
- package/dist/studio/tools.d.ts +2 -0
- package/dist/studio/tools.js +165 -0
- package/dist/studio/tools.js.map +1 -0
- package/dist/studio/voice.d.ts +150 -0
- package/dist/studio/voice.js +434 -0
- package/dist/studio/voice.js.map +1 -0
- package/dist/studio/workspace.d.ts +31 -0
- package/dist/studio/workspace.js +187 -0
- package/dist/studio/workspace.js.map +1 -0
- package/package.json +50 -4
- package/template/AGENTS.md +13 -0
- package/template/components/CATALOG.md +1306 -0
- package/template/components/README.md +61 -0
- package/template/components/STYLES.md +246 -0
- package/template/components/arcade-title/ArcadeTitle.tsx +860 -0
- package/template/components/arcade-title/meta.json +28 -0
- package/template/components/aurora/Aurora.tsx +63 -0
- package/template/components/aurora/meta.json +28 -0
- package/template/components/bar-wipe-title/BarWipeTitle.tsx +94 -0
- package/template/components/bar-wipe-title/meta.json +29 -0
- package/template/components/before-after/BeforeAfter.tsx +89 -0
- package/template/components/before-after/meta.json +233 -0
- package/template/components/bento-grid/BentoGrid.tsx +202 -0
- package/template/components/bento-grid/meta.json +25 -0
- package/template/components/blur-in-title/BlurInTitle.tsx +121 -0
- package/template/components/blur-in-title/meta.json +32 -0
- package/template/components/catalog.json +8730 -0
- package/template/components/catalog.ts +103 -0
- package/template/components/chat-thread/ChatThread.tsx +128 -0
- package/template/components/chat-thread/meta.json +24 -0
- package/template/components/checklist/Checklist.tsx +129 -0
- package/template/components/checklist/meta.json +25 -0
- package/template/components/confetti/Confetti.tsx +109 -0
- package/template/components/confetti/meta.json +28 -0
- package/template/components/countdown/Countdown.tsx +166 -0
- package/template/components/countdown/meta.json +28 -0
- package/template/components/cut-and-paste/CutAndPaste.tsx +654 -0
- package/template/components/cut-and-paste/meta.json +29 -0
- package/template/components/decode-text/DecodeText.tsx +97 -0
- package/template/components/decode-text/meta.json +29 -0
- package/template/components/editorial-quote/EditorialQuote.tsx +122 -0
- package/template/components/editorial-quote/meta.json +28 -0
- package/template/components/glitch-title/GlitchTitle.tsx +171 -0
- package/template/components/glitch-title/meta.json +32 -0
- package/template/components/halftone-wave/HalftoneWave.tsx +106 -0
- package/template/components/halftone-wave/meta.json +28 -0
- package/template/components/highlighter/Highlighter.tsx +142 -0
- package/template/components/highlighter/meta.json +28 -0
- package/template/components/hook-card/HookCard.tsx +552 -0
- package/template/components/hook-card/meta.json +304 -0
- package/template/components/index.ts +149 -0
- package/template/components/iris-wipe/IrisWipe.tsx +76 -0
- package/template/components/iris-wipe/meta.json +24 -0
- package/template/components/kinetic-poster/KineticPoster.tsx +437 -0
- package/template/components/kinetic-poster/meta.json +31 -0
- package/template/components/kinetic-punch/KineticPunch.tsx +80 -0
- package/template/components/kinetic-punch/meta.json +30 -0
- package/template/components/lava-lamp/LavaLamp.tsx +92 -0
- package/template/components/lava-lamp/meta.json +28 -0
- package/template/components/letter-cascade/LetterCascade.tsx +102 -0
- package/template/components/letter-cascade/meta.json +29 -0
- package/template/components/lib.ts +179 -0
- package/template/components/light-leak/LightLeakTransition.tsx +43 -0
- package/template/components/light-leak/meta.json +74 -0
- package/template/components/line-diagram/LineDiagram.tsx +205 -0
- package/template/components/line-diagram/meta.json +217 -0
- package/template/components/list-card/ListCard.tsx +104 -0
- package/template/components/list-card/meta.json +232 -0
- package/template/components/logo-sting/LogoSting.tsx +129 -0
- package/template/components/logo-sting/meta.json +29 -0
- package/template/components/looks.tsx +1447 -0
- package/template/components/lower-third/LowerThird.tsx +100 -0
- package/template/components/lower-third/meta.json +24 -0
- package/template/components/marquee/Marquee.tsx +100 -0
- package/template/components/marquee/meta.json +30 -0
- package/template/components/notification/Notification.tsx +115 -0
- package/template/components/notification/meta.json +27 -0
- package/template/components/outline-fill/OutlineFill.tsx +106 -0
- package/template/components/outline-fill/meta.json +28 -0
- package/template/components/panel-sweep/PanelSweep.tsx +86 -0
- package/template/components/panel-sweep/meta.json +25 -0
- package/template/components/prompt-box/PromptBox.tsx +131 -0
- package/template/components/prompt-box/meta.json +24 -0
- package/template/components/props.ts +73 -0
- package/template/components/quote-card/QuoteCard.tsx +71 -0
- package/template/components/quote-card/meta.json +216 -0
- package/template/components/shape-shift/ShapeShift.tsx +420 -0
- package/template/components/shape-shift/meta.json +31 -0
- package/template/components/slide-zoom-message/SlideZoomMessage.tsx +179 -0
- package/template/components/slide-zoom-message/meta.json +199 -0
- package/template/components/social-post/SocialPost.tsx +185 -0
- package/template/components/social-post/meta.json +30 -0
- package/template/components/split-flap/SplitFlap.tsx +191 -0
- package/template/components/split-flap/meta.json +29 -0
- package/template/components/spotlight-grid/SpotlightGrid.tsx +84 -0
- package/template/components/spotlight-grid/meta.json +25 -0
- package/template/components/stat-counter/StatCounter.tsx +117 -0
- package/template/components/stat-counter/meta.json +27 -0
- package/template/components/sticker-badge/StickerBadge.tsx +46 -0
- package/template/components/sticker-badge/meta.json +220 -0
- package/template/components/sticker-slam/StickerSlam.tsx +941 -0
- package/template/components/sticker-slam/meta.json +34 -0
- package/template/components/style-layer.tsx +233 -0
- package/template/components/styles.json +762 -0
- package/template/components/styles.ts +113 -0
- package/template/components/target-lock/TargetLock.tsx +662 -0
- package/template/components/target-lock/meta.json +32 -0
- package/template/components/text-reveal/TextReveal.tsx +99 -0
- package/template/components/text-reveal/meta.json +28 -0
- package/template/components/tile-wipe/TileWipe.tsx +75 -0
- package/template/components/tile-wipe/meta.json +24 -0
- package/template/components/type-zoom/TypeZoom.tsx +103 -0
- package/template/components/type-zoom/meta.json +27 -0
- package/template/components/types.ts +66 -0
- package/template/components/typewriter/Typewriter.tsx +112 -0
- package/template/components/typewriter/meta.json +29 -0
- package/template/components/word-pop/WordPop.tsx +59 -0
- package/template/components/word-pop/meta.json +237 -0
- package/template/components/word-stack/WordStack.tsx +122 -0
- package/template/components/word-stack/meta.json +27 -0
- package/template/components/word-swap/WordSwap.tsx +127 -0
- package/template/components/word-swap/meta.json +30 -0
- package/template/presets/charcoal-sketch/PROMPT.md +48 -0
- package/template/presets/charcoal-sketch/assets/paper/grain-0.png +0 -0
- package/template/presets/charcoal-sketch/assets/paper/grain-1.png +0 -0
- package/template/presets/charcoal-sketch/assets/paper/grain-2.png +0 -0
- package/template/presets/charcoal-sketch/assets/paper/sketch-paper.jpg +0 -0
- package/template/presets/charcoal-sketch/assets/paper/smudge.png +0 -0
- package/template/presets/charcoal-sketch/poster.jpg +0 -0
- package/template/presets/charcoal-sketch/preset.json +17 -0
- package/template/presets/charcoal-sketch/preview.mp4 +0 -0
- package/template/presets/charcoal-sketch/scenes/Grain.tsx +23 -0
- package/template/presets/charcoal-sketch/scenes/Paper.tsx +17 -0
- package/template/presets/charcoal-sketch/scenes/examples/Agents.tsx +100 -0
- package/template/presets/charcoal-sketch/scenes/examples/Approvals.tsx +110 -0
- package/template/presets/charcoal-sketch/scenes/examples/Blog.tsx +105 -0
- package/template/presets/charcoal-sketch/scenes/examples/EndCard.tsx +41 -0
- package/template/presets/charcoal-sketch/scenes/examples/Hook.tsx +130 -0
- package/template/presets/charcoal-sketch/scenes/examples/Ideas.tsx +92 -0
- package/template/presets/charcoal-sketch/scenes/examples/Posting.tsx +128 -0
- package/template/presets/charcoal-sketch/scenes/lib/painfix.tsx +119 -0
- package/template/presets/charcoal-sketch/scenes/lib/sketch.tsx +291 -0
- package/template/presets/charcoal-sketch/scripts/build_layers.example.py +193 -0
- package/template/presets/charcoal-sketch/scripts/duck_music.py +34 -0
- package/template/presets/charcoal-sketch/scripts/make_textures.py +93 -0
- package/template/presets/punk-cut-paper/PROMPT.md +37 -0
- package/template/presets/punk-cut-paper/assets/paper/desk-cream.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/grain-overlay.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/halftone-black.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/halftone-red.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/halftone-yellow.png +0 -0
- package/template/presets/punk-cut-paper/assets/paper/kraft.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/newsprint.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/paper-cream.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/paper-white.jpg +0 -0
- package/template/presets/punk-cut-paper/assets/paper/tape.png +0 -0
- package/template/presets/punk-cut-paper/build_layers.example.py +150 -0
- package/template/presets/punk-cut-paper/poster.jpg +0 -0
- package/template/presets/punk-cut-paper/preset.json +15 -0
- package/template/presets/punk-cut-paper/preview.mp4 +0 -0
- package/template/presets/punk-cut-paper/scenes/Backdrop.tsx +76 -0
- package/template/presets/punk-cut-paper/scenes/Motif.tsx +376 -0
- package/template/presets/punk-cut-paper/scenes/Photo.tsx +73 -0
- package/template/presets/punk-cut-paper/scenes/Ransom.tsx +119 -0
- package/template/presets/punk-cut-paper/scenes/Xerox.tsx +31 -0
- package/template/presets/punk-cut-paper/scenes/lib/punk.tsx +208 -0
- package/template/runtime/composition.tsx +920 -0
- package/template/runtime/helpers.tsx +228 -0
- package/template/runtime/index.tsx +22 -0
- package/template/runtime/types.ts +248 -0
- package/template/skill/SKILL.md +149 -0
- package/template/skill/references/browser-export.md +61 -0
- package/template/skill/references/components.md +38 -0
- package/template/skill/references/craft.md +53 -0
- package/template/skill/references/cursor.md +91 -0
- package/template/skill/references/footage.md +73 -0
- package/template/skill/references/format.md +140 -0
- package/template/skill/references/presets.md +56 -0
- package/template/skill/references/sound.md +128 -0
- package/template/starter/.studio/chat.json +1 -0
- package/template/starter/assets/.keep +0 -0
- package/template/starter/layers.json +46 -0
- package/template/starter/notes.md +4 -0
- package/template/starter/project.json +13 -0
- package/template/starter/renders/.keep +0 -0
- package/template/starter/scenes/Title.tsx +38 -0
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, isAbsolute, join, relative, sep } from "node:path";
|
|
4
|
+
import { debugLog } from "../log.js";
|
|
5
|
+
import { getAgent } from "./agents/index.js";
|
|
6
|
+
import { atomicWrite, projectDir, StudioError } from "./projects.js";
|
|
7
|
+
import { VOICE_KEY_ENV_VARS } from "./voice.js";
|
|
8
|
+
import { DETACH_FOR_GROUP_KILL, killTree, spawnCommand } from "./proc.js";
|
|
9
|
+
const MAX_MESSAGES = 400;
|
|
10
|
+
/** The agent of chats saved before the `agent` field existed. */
|
|
11
|
+
const LEGACY_AGENT = "claude";
|
|
12
|
+
const FILE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
|
|
13
|
+
const IMAGE_FILE = /\.(png|jpe?g|webp|gif)$/i;
|
|
14
|
+
/** A frame the bridge saved for the agent (see persistAgentFrameResult). */
|
|
15
|
+
const SAVED_FRAME = /[\\/]agentcut-frame-[\w-]+\.(png|jpe?g|webp)$/i;
|
|
16
|
+
/** Every saved-frame `filePath` in a tool result (text blocks hold JSON, sometimes JSON in JSON). */
|
|
17
|
+
function collectFramePaths(value, out, depth) {
|
|
18
|
+
if (depth > 12 || out.size >= 24)
|
|
19
|
+
return;
|
|
20
|
+
if (typeof value === "string") {
|
|
21
|
+
const trimmed = value.trim();
|
|
22
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
23
|
+
try {
|
|
24
|
+
collectFramePaths(JSON.parse(trimmed), out, depth + 1);
|
|
25
|
+
}
|
|
26
|
+
catch { }
|
|
27
|
+
}
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (Array.isArray(value)) {
|
|
31
|
+
for (const item of value)
|
|
32
|
+
collectFramePaths(item, out, depth + 1);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (!value || typeof value !== "object")
|
|
36
|
+
return;
|
|
37
|
+
for (const [key, item] of Object.entries(value)) {
|
|
38
|
+
if (key === "filePath" && typeof item === "string" && SAVED_FRAME.test(item))
|
|
39
|
+
out.add(item);
|
|
40
|
+
else
|
|
41
|
+
collectFramePaths(item, out, depth + 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const MAX_CHAT_FRAMES = 400;
|
|
45
|
+
function asRecord(value) {
|
|
46
|
+
return value && typeof value === "object" ? value : {};
|
|
47
|
+
}
|
|
48
|
+
export class ChatEngine {
|
|
49
|
+
deps;
|
|
50
|
+
turns = new Map();
|
|
51
|
+
/** One agent at a time: messages wait here and run in order when the current turn ends. */
|
|
52
|
+
queue = [];
|
|
53
|
+
constructor(deps) {
|
|
54
|
+
this.deps = deps;
|
|
55
|
+
}
|
|
56
|
+
chatPath(slug) {
|
|
57
|
+
return join(projectDir(this.deps.paths, slug), ".studio", "chat.json");
|
|
58
|
+
}
|
|
59
|
+
load(slug) {
|
|
60
|
+
try {
|
|
61
|
+
const raw = JSON.parse(readFileSync(this.chatPath(slug), "utf8"));
|
|
62
|
+
if (raw && Array.isArray(raw.messages)) {
|
|
63
|
+
const sessionId = raw.sessionId ?? null;
|
|
64
|
+
return { version: 1, sessionId, agent: raw.agent ?? (sessionId ? LEGACY_AGENT : null), messages: raw.messages };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
68
|
+
return { version: 1, sessionId: null, agent: null, messages: [] };
|
|
69
|
+
}
|
|
70
|
+
save(slug, file) {
|
|
71
|
+
const path = this.chatPath(slug);
|
|
72
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
73
|
+
const trimmed = { ...file, messages: file.messages.slice(-MAX_MESSAGES) };
|
|
74
|
+
atomicWrite(path, `${JSON.stringify(trimmed, null, 2)}\n`);
|
|
75
|
+
}
|
|
76
|
+
upsertMessage(slug, message) {
|
|
77
|
+
const file = this.load(slug);
|
|
78
|
+
const index = file.messages.findIndex((m) => m.id === message.id);
|
|
79
|
+
if (index >= 0)
|
|
80
|
+
file.messages[index] = message;
|
|
81
|
+
else
|
|
82
|
+
file.messages.push(message);
|
|
83
|
+
this.save(slug, file);
|
|
84
|
+
}
|
|
85
|
+
saveSession(slug, agentId, sessionId) {
|
|
86
|
+
const file = this.load(slug);
|
|
87
|
+
if (file.sessionId === sessionId && file.agent === agentId)
|
|
88
|
+
return;
|
|
89
|
+
file.sessionId = sessionId;
|
|
90
|
+
file.agent = agentId;
|
|
91
|
+
this.save(slug, file);
|
|
92
|
+
}
|
|
93
|
+
history(slug) {
|
|
94
|
+
const file = this.load(slug);
|
|
95
|
+
// Queued messages from a previous helper run are gone from memory: show them as not sent.
|
|
96
|
+
let stale = false;
|
|
97
|
+
for (const message of file.messages) {
|
|
98
|
+
if (message.status === "queued" && !this.queue.some((q) => q.messageId === message.id)) {
|
|
99
|
+
message.status = "cancelled";
|
|
100
|
+
stale = true;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (stale)
|
|
104
|
+
this.save(slug, file);
|
|
105
|
+
return {
|
|
106
|
+
sessionId: file.sessionId,
|
|
107
|
+
agent: file.agent,
|
|
108
|
+
messages: file.messages,
|
|
109
|
+
running: this.turns.has(slug) ? this.turns.get(slug)?.message.id : null,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
reset(slug) {
|
|
113
|
+
this.dropQueued(slug);
|
|
114
|
+
this.cancel(slug);
|
|
115
|
+
this.save(slug, { version: 1, sessionId: null, agent: null, messages: [] });
|
|
116
|
+
this.deps.emit("studio.chat", { slug, kind: "reset" });
|
|
117
|
+
return { ok: true };
|
|
118
|
+
}
|
|
119
|
+
cancel(slug) {
|
|
120
|
+
const turn = this.turns.get(slug);
|
|
121
|
+
if (!turn)
|
|
122
|
+
return { ok: true, cancelled: false };
|
|
123
|
+
turn.cancelled = true;
|
|
124
|
+
killTree(turn.child);
|
|
125
|
+
return { ok: true, cancelled: true };
|
|
126
|
+
}
|
|
127
|
+
/** The running turn (there is at most one). */
|
|
128
|
+
runningSlug() {
|
|
129
|
+
return [...this.turns.keys()][0] ?? null;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The agent created a new project from a chat in another one: the conversation moves with
|
|
133
|
+
* it, so the new project's chat shows the work in progress and later messages resume
|
|
134
|
+
* the same session there.
|
|
135
|
+
*/
|
|
136
|
+
moveRunningTurn(to) {
|
|
137
|
+
const from = this.runningSlug();
|
|
138
|
+
if (!from || from === to)
|
|
139
|
+
return false;
|
|
140
|
+
const turn = this.turns.get(from);
|
|
141
|
+
const source = this.load(from);
|
|
142
|
+
const target = this.load(to);
|
|
143
|
+
const moving = source.messages.filter((m) => !target.messages.some((t) => t.id === m.id));
|
|
144
|
+
// The whole conversation goes along when the new chat is empty; otherwise just this turn.
|
|
145
|
+
const userIndex = source.messages.findIndex((m) => m.id === turn.message.id) - 1;
|
|
146
|
+
const turnMessages = source.messages.slice(Math.max(0, userIndex));
|
|
147
|
+
target.messages = target.messages.length === 0 ? moving : [...target.messages, ...turnMessages];
|
|
148
|
+
target.sessionId = source.sessionId;
|
|
149
|
+
target.agent = source.agent;
|
|
150
|
+
this.save(to, target);
|
|
151
|
+
// Leave a pointer in the old chat instead of the moved turn.
|
|
152
|
+
source.messages = source.messages.filter((m) => !turnMessages.some((t) => t.id === m.id));
|
|
153
|
+
source.messages.push({
|
|
154
|
+
id: randomUUID(),
|
|
155
|
+
role: "assistant",
|
|
156
|
+
at: Date.now(),
|
|
157
|
+
agent: turn.agent.id,
|
|
158
|
+
status: "done",
|
|
159
|
+
parts: [{ type: "text", text: `${turn.agent.name} created the project **${to}** and moved this conversation there.` }],
|
|
160
|
+
});
|
|
161
|
+
this.save(from, source);
|
|
162
|
+
this.turns.delete(from);
|
|
163
|
+
turn.slug = to;
|
|
164
|
+
this.turns.set(to, turn);
|
|
165
|
+
// Messages queued in the old chat follow the conversation.
|
|
166
|
+
const followers = this.queue.filter((q) => q.slug === from);
|
|
167
|
+
if (followers.length) {
|
|
168
|
+
const src = this.load(from);
|
|
169
|
+
const dst = this.load(to);
|
|
170
|
+
for (const item of followers) {
|
|
171
|
+
const message = src.messages.find((m) => m.id === item.messageId);
|
|
172
|
+
if (message && !dst.messages.some((m) => m.id === message.id))
|
|
173
|
+
dst.messages.push(message);
|
|
174
|
+
src.messages = src.messages.filter((m) => m.id !== item.messageId);
|
|
175
|
+
item.slug = to;
|
|
176
|
+
}
|
|
177
|
+
this.save(from, src);
|
|
178
|
+
this.save(to, dst);
|
|
179
|
+
}
|
|
180
|
+
debugLog(`chat moved from ${from} to ${to}`);
|
|
181
|
+
this.deps.emit("studio.chat", { slug: from, kind: "reload" });
|
|
182
|
+
this.deps.emit("studio.chat", { slug: to, kind: "reload" });
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
cancelAll() {
|
|
186
|
+
for (const slug of [...this.turns.keys()])
|
|
187
|
+
this.cancel(slug);
|
|
188
|
+
}
|
|
189
|
+
/** The agent for a message: the one the page picked, else the chat's, else the default. */
|
|
190
|
+
async resolveAgent(slug, requested) {
|
|
191
|
+
const agents = await this.deps.getAgents();
|
|
192
|
+
const id = (typeof requested === "string" && requested) || this.load(slug).agent || (await this.deps.defaultAgent()) || agents[0]?.id;
|
|
193
|
+
const adapter = id ? getAgent(id) : undefined;
|
|
194
|
+
const info = agents.find((agent) => agent.id === id);
|
|
195
|
+
if (!adapter || !info)
|
|
196
|
+
throw new StudioError(`Unknown agent "${String(id)}".`, "no_agent");
|
|
197
|
+
if (!info.found || !info.path) {
|
|
198
|
+
throw new StudioError(info.error ?? `${info.product} was not found.`, "no_agent");
|
|
199
|
+
}
|
|
200
|
+
return { adapter, info, path: info.path, agents };
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The context block sent with a message, plus the images to attach. Captured when the user
|
|
204
|
+
* sends it (a queued message keeps the playhead it was sent with).
|
|
205
|
+
*/
|
|
206
|
+
buildContext(slug, context, agent) {
|
|
207
|
+
const page = { ...(this.deps.getPageContext() ?? {}), ...context };
|
|
208
|
+
const dir = projectDir(this.deps.paths, slug);
|
|
209
|
+
const lines = [
|
|
210
|
+
`<studio-context>`,
|
|
211
|
+
`You are working inside Agentcut. The user watches the studio page: chat, live preview, timeline. Follow the agentcut skill.`,
|
|
212
|
+
`Active project: ${slug} (folder: ${dir})`,
|
|
213
|
+
];
|
|
214
|
+
if (this.deps.addDirs.length) {
|
|
215
|
+
lines.push(`Other folders you can read (e.g. the app's source repo; never change files there, not even with shell commands): ${this.deps.addDirs.join(", ")}`);
|
|
216
|
+
}
|
|
217
|
+
if (typeof page.variant === "string")
|
|
218
|
+
lines.push(`Variant on screen: ${page.variant}`);
|
|
219
|
+
if (typeof page.playheadFrame === "number") {
|
|
220
|
+
const fps = typeof page.fps === "number" ? page.fps : 30;
|
|
221
|
+
lines.push(`Playhead: frame ${page.playheadFrame} (${(page.playheadFrame / fps).toFixed(2)} s)`);
|
|
222
|
+
}
|
|
223
|
+
if (Array.isArray(page.selectedClipIds) && page.selectedClipIds.length > 0) {
|
|
224
|
+
lines.push(`Selected clips: ${page.selectedClipIds.join(", ")}`);
|
|
225
|
+
}
|
|
226
|
+
const attachments = Array.isArray(context.attachments) ? context.attachments.filter((a) => typeof a === "string") : [];
|
|
227
|
+
const images = attachments.map((attachment) => join(dir, attachment));
|
|
228
|
+
for (const image of images) {
|
|
229
|
+
lines.push(`Attached image (${agent.imageHint}): ${image}`);
|
|
230
|
+
}
|
|
231
|
+
const references = (Array.isArray(context.references) ? context.references : [])
|
|
232
|
+
.map((value) => asRecord(value))
|
|
233
|
+
.filter((ref) => typeof ref.path === "string" && !String(ref.path).includes(".."))
|
|
234
|
+
.slice(0, 12)
|
|
235
|
+
.map((ref) => ({ path: String(ref.path), kind: typeof ref.kind === "string" ? ref.kind : "other" }));
|
|
236
|
+
if (references.length) {
|
|
237
|
+
lines.push(`The user is pointing at these project files (paths relative to the project folder):`);
|
|
238
|
+
for (const ref of references) {
|
|
239
|
+
const hint = ref.kind === "image" ? ` (an image: ${agent.imageHint})` : ref.kind === "audio" ? " (audio: use the listen/media tools)" : "";
|
|
240
|
+
lines.push(`- ${ref.path} [${ref.kind}]${hint}`);
|
|
241
|
+
if (ref.kind === "image")
|
|
242
|
+
images.push(join(dir, ref.path));
|
|
243
|
+
}
|
|
244
|
+
lines.push(`"Here", "now" or "at the playhead" means the playhead frame above.`);
|
|
245
|
+
}
|
|
246
|
+
lines.push(`</studio-context>`);
|
|
247
|
+
return { text: lines.join("\n"), attachments, references, images: images.filter((image) => existsSync(image)) };
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* The conversation so far, for an agent that takes over a chat another agent started
|
|
251
|
+
* (sessions can't move between CLIs). The project files stay the source of truth.
|
|
252
|
+
*/
|
|
253
|
+
handoff(file, agents, to, skipId) {
|
|
254
|
+
const nameOf = (id) => agents.find((agent) => agent.id === id)?.name ?? "Assistant";
|
|
255
|
+
const lines = [];
|
|
256
|
+
for (const message of file.messages.slice(-16)) {
|
|
257
|
+
if (message.id === skipId || message.status === "queued")
|
|
258
|
+
continue;
|
|
259
|
+
const text = message.role === "user"
|
|
260
|
+
? (message.text ?? "")
|
|
261
|
+
: (message.parts ?? [])
|
|
262
|
+
.map((part) => (part.type === "text" ? part.text : ""))
|
|
263
|
+
.join("")
|
|
264
|
+
.trim();
|
|
265
|
+
if (!text.trim())
|
|
266
|
+
continue;
|
|
267
|
+
const who = message.role === "user" ? "User" : nameOf(message.agent ?? file.agent ?? undefined);
|
|
268
|
+
lines.push(`${who}: ${text.length > 700 ? `${text.slice(0, 700)}…` : text}`);
|
|
269
|
+
}
|
|
270
|
+
if (!lines.length)
|
|
271
|
+
return "";
|
|
272
|
+
return [
|
|
273
|
+
`<earlier-conversation>`,
|
|
274
|
+
`This chat was started with ${nameOf(file.agent ?? undefined)}; you (${to.name}) are taking over. Recent messages, for context. Re-read the project files before changing them.`,
|
|
275
|
+
...lines,
|
|
276
|
+
`</earlier-conversation>`,
|
|
277
|
+
].join("\n");
|
|
278
|
+
}
|
|
279
|
+
async send(slug, text, context, agentId) {
|
|
280
|
+
const trimmed = text.trim();
|
|
281
|
+
if (!trimmed)
|
|
282
|
+
throw new StudioError("Type a message first.", "empty");
|
|
283
|
+
const resolved = await this.resolveAgent(slug, agentId);
|
|
284
|
+
const { adapter } = resolved;
|
|
285
|
+
// The context (playhead, selection, pointed-at files) is taken now, when the user sent it.
|
|
286
|
+
const { attachments, references } = this.buildContext(slug, context, adapter);
|
|
287
|
+
const busy = this.turns.size > 0 || this.queue.length > 0;
|
|
288
|
+
const userMessage = {
|
|
289
|
+
id: randomUUID(),
|
|
290
|
+
role: "user",
|
|
291
|
+
at: Date.now(),
|
|
292
|
+
text: trimmed,
|
|
293
|
+
attachments: attachments.length ? attachments : undefined,
|
|
294
|
+
references: references.length ? references : undefined,
|
|
295
|
+
...(busy ? { status: "queued" } : {}),
|
|
296
|
+
};
|
|
297
|
+
this.upsertMessage(slug, userMessage);
|
|
298
|
+
this.deps.emit("studio.chat", { slug, kind: "user", message: userMessage });
|
|
299
|
+
// Frozen now: a queued message keeps the playhead and selection it was sent with.
|
|
300
|
+
const frozen = { ...(this.deps.getPageContext() ?? {}), ...context };
|
|
301
|
+
if (busy) {
|
|
302
|
+
// One agent at a time: two runs writing the same workspace overwrite each other.
|
|
303
|
+
this.queue.push({ slug, messageId: userMessage.id, text: trimmed, agentId: adapter.id, context: frozen });
|
|
304
|
+
debugLog(`chat ${slug}: queued (${this.queue.length} waiting)`);
|
|
305
|
+
return { queued: true, position: this.queue.length, userMessageId: userMessage.id };
|
|
306
|
+
}
|
|
307
|
+
const turnId = this.startTurn(slug, resolved, frozen, trimmed, userMessage.id);
|
|
308
|
+
return { turnId, userMessageId: userMessage.id };
|
|
309
|
+
}
|
|
310
|
+
/** Synchronous once the agent is resolved, so no other turn can start in between. */
|
|
311
|
+
startTurn(slug, resolved, context, text, userMessageId) {
|
|
312
|
+
const { adapter, path, agents } = resolved;
|
|
313
|
+
const { text: contextText, images } = this.buildContext(slug, context, adapter);
|
|
314
|
+
const file = this.load(slug);
|
|
315
|
+
// Another agent owns the saved session: start a new one and pass the conversation along.
|
|
316
|
+
const switching = Boolean(file.sessionId) && file.agent !== adapter.id;
|
|
317
|
+
const handoff = switching ? this.handoff(file, agents, adapter, userMessageId) : "";
|
|
318
|
+
const assistant = {
|
|
319
|
+
id: randomUUID(),
|
|
320
|
+
role: "assistant",
|
|
321
|
+
at: Date.now(),
|
|
322
|
+
agent: adapter.id,
|
|
323
|
+
parts: [],
|
|
324
|
+
status: "running",
|
|
325
|
+
};
|
|
326
|
+
this.upsertMessage(slug, assistant);
|
|
327
|
+
this.deps.emit("studio.chat", { slug, kind: "start", message: assistant });
|
|
328
|
+
const prompt = [handoff, contextText, text].filter(Boolean).join("\n\n");
|
|
329
|
+
this.startProcess(slug, adapter, path, prompt, images, assistant, switching ? null : file.sessionId, false);
|
|
330
|
+
return assistant.id;
|
|
331
|
+
}
|
|
332
|
+
/** Start the next queued message once nothing is running. */
|
|
333
|
+
async drain() {
|
|
334
|
+
if (this.turns.size > 0)
|
|
335
|
+
return;
|
|
336
|
+
const next = this.queue.shift();
|
|
337
|
+
if (!next)
|
|
338
|
+
return;
|
|
339
|
+
const file = this.load(next.slug);
|
|
340
|
+
const message = file.messages.find((m) => m.id === next.messageId);
|
|
341
|
+
if (message) {
|
|
342
|
+
// It moves down to where the answer will start, so each answer follows its message.
|
|
343
|
+
delete message.status;
|
|
344
|
+
message.at = Date.now();
|
|
345
|
+
file.messages = [...file.messages.filter((m) => m.id !== message.id), message];
|
|
346
|
+
this.save(next.slug, file);
|
|
347
|
+
this.deps.emit("studio.chat", { slug: next.slug, kind: "dequeue", message });
|
|
348
|
+
}
|
|
349
|
+
try {
|
|
350
|
+
const resolved = await this.resolveAgent(next.slug, next.agentId);
|
|
351
|
+
if (this.turns.size > 0) {
|
|
352
|
+
this.queue.unshift(next);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
debugLog(`chat ${next.slug}: starting queued message (${this.queue.length} still waiting)`);
|
|
356
|
+
this.startTurn(next.slug, resolved, next.context, next.text, next.messageId);
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
// The agent went missing since the message was queued: say so in the chat, then go on.
|
|
360
|
+
const failed = {
|
|
361
|
+
id: randomUUID(),
|
|
362
|
+
role: "assistant",
|
|
363
|
+
at: Date.now(),
|
|
364
|
+
agent: next.agentId,
|
|
365
|
+
status: "error",
|
|
366
|
+
error: error instanceof Error ? error.message : String(error),
|
|
367
|
+
};
|
|
368
|
+
this.upsertMessage(next.slug, failed);
|
|
369
|
+
this.deps.emit("studio.chat", { slug: next.slug, kind: "done", message: failed });
|
|
370
|
+
void this.drain();
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
/** The waiting messages, in order (for the page). */
|
|
374
|
+
queued() {
|
|
375
|
+
return this.queue.map((q, index) => ({ slug: q.slug, messageId: q.messageId, position: index + 1 }));
|
|
376
|
+
}
|
|
377
|
+
/** Edit a message that hasn't started yet. */
|
|
378
|
+
editQueued(slug, messageId, text) {
|
|
379
|
+
const item = this.queue.find((q) => q.slug === slug && q.messageId === messageId);
|
|
380
|
+
const trimmed = text.trim();
|
|
381
|
+
if (!item)
|
|
382
|
+
throw new StudioError("That message already started or was removed.", "not_queued");
|
|
383
|
+
if (!trimmed)
|
|
384
|
+
throw new StudioError("Type a message first.", "empty");
|
|
385
|
+
item.text = trimmed;
|
|
386
|
+
const file = this.load(slug);
|
|
387
|
+
const message = file.messages.find((m) => m.id === messageId);
|
|
388
|
+
if (message) {
|
|
389
|
+
message.text = trimmed;
|
|
390
|
+
this.save(slug, file);
|
|
391
|
+
this.deps.emit("studio.chat", { slug, kind: "update", message });
|
|
392
|
+
}
|
|
393
|
+
return { ok: true };
|
|
394
|
+
}
|
|
395
|
+
/** Take a message out of the queue (it never reaches the agent). */
|
|
396
|
+
removeQueued(slug, messageId) {
|
|
397
|
+
const index = this.queue.findIndex((q) => q.slug === slug && q.messageId === messageId);
|
|
398
|
+
if (index < 0)
|
|
399
|
+
return { ok: true, removed: false };
|
|
400
|
+
this.queue.splice(index, 1);
|
|
401
|
+
const file = this.load(slug);
|
|
402
|
+
file.messages = file.messages.filter((m) => m.id !== messageId);
|
|
403
|
+
this.save(slug, file);
|
|
404
|
+
this.deps.emit("studio.chat", { slug, kind: "remove", messageId });
|
|
405
|
+
return { ok: true, removed: true };
|
|
406
|
+
}
|
|
407
|
+
/** "Stop and send this now": move it to the front and stop the running turn. */
|
|
408
|
+
sendQueuedNow(slug, messageId) {
|
|
409
|
+
const index = this.queue.findIndex((q) => q.slug === slug && q.messageId === messageId);
|
|
410
|
+
if (index < 0)
|
|
411
|
+
throw new StudioError("That message already started or was removed.", "not_queued");
|
|
412
|
+
const [item] = this.queue.splice(index, 1);
|
|
413
|
+
this.queue.unshift(item);
|
|
414
|
+
const running = this.runningSlug();
|
|
415
|
+
if (running)
|
|
416
|
+
this.cancel(running);
|
|
417
|
+
else
|
|
418
|
+
void this.drain();
|
|
419
|
+
return { ok: true };
|
|
420
|
+
}
|
|
421
|
+
/** Forget the messages waiting for a project (it is being deleted or reset). */
|
|
422
|
+
dropQueued(slug) {
|
|
423
|
+
for (const item of this.queue.filter((q) => q.slug === slug))
|
|
424
|
+
this.removeQueued(slug, item.messageId);
|
|
425
|
+
}
|
|
426
|
+
startProcess(slug, agent, agentPath, prompt, images, assistant, sessionId, isRetry) {
|
|
427
|
+
const args = agent.buildArgs({
|
|
428
|
+
prompt,
|
|
429
|
+
sessionId,
|
|
430
|
+
images,
|
|
431
|
+
workspace: this.deps.paths.root,
|
|
432
|
+
mcp: this.deps.mcp,
|
|
433
|
+
mcpConfigPath: this.deps.paths.mcpConfig,
|
|
434
|
+
allowShell: this.deps.allowBash,
|
|
435
|
+
readDirs: this.deps.addDirs,
|
|
436
|
+
});
|
|
437
|
+
const child = spawnCommand(agentPath, args, {
|
|
438
|
+
cwd: this.deps.paths.root,
|
|
439
|
+
env: {
|
|
440
|
+
// Voice-provider keys stay in the helper: the agent (and the tools it runs) never get them.
|
|
441
|
+
...Object.fromEntries(Object.entries(process.env).filter(([name]) => !VOICE_KEY_ENV_VARS.includes(name))),
|
|
442
|
+
AGENTCUT_WORKSPACE: this.deps.paths.root,
|
|
443
|
+
AGENTCUT_PROJECT: slug,
|
|
444
|
+
},
|
|
445
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
446
|
+
detached: DETACH_FOR_GROUP_KILL,
|
|
447
|
+
});
|
|
448
|
+
const turn = {
|
|
449
|
+
slug,
|
|
450
|
+
agent,
|
|
451
|
+
parser: agent.createParser(),
|
|
452
|
+
message: assistant,
|
|
453
|
+
child,
|
|
454
|
+
startedAt: Date.now(),
|
|
455
|
+
cancelled: false,
|
|
456
|
+
stderr: "",
|
|
457
|
+
lastError: null,
|
|
458
|
+
gotResult: false,
|
|
459
|
+
retriedWithoutResume: isRetry,
|
|
460
|
+
};
|
|
461
|
+
this.turns.set(slug, turn);
|
|
462
|
+
child.stdin?.on("error", () => undefined);
|
|
463
|
+
child.stdin?.end(prompt);
|
|
464
|
+
const handleLine = (line) => {
|
|
465
|
+
for (const event of turn.parser.line(line))
|
|
466
|
+
this.handleEvent(turn, event);
|
|
467
|
+
};
|
|
468
|
+
let buffer = "";
|
|
469
|
+
child.stdout?.setEncoding("utf8");
|
|
470
|
+
child.stdout?.on("data", (chunk) => {
|
|
471
|
+
buffer += chunk;
|
|
472
|
+
let newline = buffer.indexOf("\n");
|
|
473
|
+
while (newline >= 0) {
|
|
474
|
+
const line = buffer.slice(0, newline).trim();
|
|
475
|
+
buffer = buffer.slice(newline + 1);
|
|
476
|
+
if (line)
|
|
477
|
+
handleLine(line);
|
|
478
|
+
newline = buffer.indexOf("\n");
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
child.stderr?.setEncoding("utf8");
|
|
482
|
+
child.stderr?.on("data", (chunk) => {
|
|
483
|
+
turn.stderr = (turn.stderr + chunk).slice(-4000);
|
|
484
|
+
});
|
|
485
|
+
child.on("error", (error) => {
|
|
486
|
+
turn.stderr = `${turn.stderr}\n${error.message}`.slice(-4000);
|
|
487
|
+
});
|
|
488
|
+
child.on("close", (code) => {
|
|
489
|
+
if (buffer.trim())
|
|
490
|
+
handleLine(buffer.trim());
|
|
491
|
+
const slug = turn.slug; // may have moved to a new project mid-turn
|
|
492
|
+
this.turns.delete(slug);
|
|
493
|
+
if (!turn.cancelled && !turn.gotResult && sessionId && agent.isLostSession(turn.stderr) && !turn.retriedWithoutResume) {
|
|
494
|
+
// The saved session is gone (e.g. cleared); start a fresh one.
|
|
495
|
+
debugLog(`chat ${slug}: resume failed, starting a new session`);
|
|
496
|
+
this.saveSession(slug, agent.id, null);
|
|
497
|
+
this.startProcess(slug, agent, agentPath, prompt, images, assistant, null, true);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (turn.cancelled) {
|
|
501
|
+
assistant.status = "cancelled";
|
|
502
|
+
}
|
|
503
|
+
else if (!turn.gotResult) {
|
|
504
|
+
assistant.status = "error";
|
|
505
|
+
assistant.error =
|
|
506
|
+
turn.lastError ?? (turn.stderr.trim().split(/\r?\n/).slice(-6).join("\n") || `${agent.product} exited with code ${code}.`);
|
|
507
|
+
}
|
|
508
|
+
this.finishRunningTools(assistant, assistant.status === "done" ? "done" : "error");
|
|
509
|
+
this.upsertMessage(slug, assistant);
|
|
510
|
+
this.deps.emit("studio.chat", { slug, kind: "done", message: assistant });
|
|
511
|
+
void this.drain().catch((error) => debugLog(`chat queue: ${error instanceof Error ? error.message : String(error)}`));
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
finishRunningTools(message, status) {
|
|
515
|
+
for (const part of message.parts ?? []) {
|
|
516
|
+
if (part.type === "tool" && part.status === "running")
|
|
517
|
+
part.status = status;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
relativeFile(slug, file) {
|
|
521
|
+
if (typeof file !== "string")
|
|
522
|
+
return undefined;
|
|
523
|
+
const dir = projectDir(this.deps.paths, slug);
|
|
524
|
+
const rel = relative(dir, file);
|
|
525
|
+
if (!rel.startsWith("..") && !rel.includes(`..${sep}`))
|
|
526
|
+
return rel.split(sep).join("/");
|
|
527
|
+
const fromRoot = relative(this.deps.paths.root, file);
|
|
528
|
+
return fromRoot.startsWith("..") ? file : fromRoot.split(sep).join("/");
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* The pictures a step showed the agent, so the chat can show them too: frames the studio captured
|
|
532
|
+
* (copied out of the bridge's scratch folder, which it prunes) and images it read from the project.
|
|
533
|
+
* (The folder keeps its old name so earlier chats still find their pictures.)
|
|
534
|
+
*/
|
|
535
|
+
imagesFor(slug, part, content) {
|
|
536
|
+
try {
|
|
537
|
+
if (part.name === "Read") {
|
|
538
|
+
return part.file && IMAGE_FILE.test(part.file) && !isAbsolute(part.file) && !part.file.startsWith("..") ? [part.file] : [];
|
|
539
|
+
}
|
|
540
|
+
if (!part.name.startsWith("mcp__agentcut__"))
|
|
541
|
+
return [];
|
|
542
|
+
const found = new Set();
|
|
543
|
+
collectFramePaths(content, found, 0);
|
|
544
|
+
if (found.size === 0)
|
|
545
|
+
return [];
|
|
546
|
+
const dir = join(projectDir(this.deps.paths, slug), ".studio", "attachments", "claude-frames");
|
|
547
|
+
mkdirSync(dir, { recursive: true });
|
|
548
|
+
const out = [];
|
|
549
|
+
for (const source of [...found].slice(0, 24)) {
|
|
550
|
+
if (!existsSync(source))
|
|
551
|
+
continue;
|
|
552
|
+
const name = basename(source);
|
|
553
|
+
copyFileSync(source, join(dir, name));
|
|
554
|
+
out.push(`.studio/attachments/claude-frames/${name}`);
|
|
555
|
+
}
|
|
556
|
+
this.pruneFrames(dir);
|
|
557
|
+
return out;
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
debugLog(`chat images ${error instanceof Error ? error.message : String(error)}`);
|
|
561
|
+
return [];
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
pruneFrames(dir) {
|
|
565
|
+
const files = readdirSync(dir)
|
|
566
|
+
.map((name) => ({ name, mtime: statSync(join(dir, name)).mtimeMs }))
|
|
567
|
+
.sort((a, b) => b.mtime - a.mtime);
|
|
568
|
+
for (const old of files.slice(MAX_CHAT_FRAMES))
|
|
569
|
+
rmSync(join(dir, old.name), { force: true });
|
|
570
|
+
}
|
|
571
|
+
toolSummary(slug, name, input) {
|
|
572
|
+
const file = this.relativeFile(slug, input.file_path ?? input.path ?? input.notebook_path);
|
|
573
|
+
switch (name) {
|
|
574
|
+
case "Write":
|
|
575
|
+
return { summary: `Wrote ${file ?? "a file"}`, file };
|
|
576
|
+
case "Edit":
|
|
577
|
+
case "MultiEdit":
|
|
578
|
+
return { summary: `Edited ${file ?? "a file"}`, file };
|
|
579
|
+
case "Read":
|
|
580
|
+
return { summary: `Read ${file ?? "a file"}`, file };
|
|
581
|
+
case "Glob":
|
|
582
|
+
case "Grep":
|
|
583
|
+
return { summary: `${name} ${String(input.pattern ?? "").slice(0, 60)}` };
|
|
584
|
+
case "Bash":
|
|
585
|
+
return { summary: `Ran ${String(input.description ?? input.command ?? "").trim().split(/\r?\n/)[0].slice(0, 80)}` };
|
|
586
|
+
case "WebSearch":
|
|
587
|
+
return { summary: `Searched “${String(input.query ?? "").slice(0, 60)}”` };
|
|
588
|
+
case "WebFetch":
|
|
589
|
+
return { summary: `Fetched ${String(input.url ?? "").slice(0, 80)}` };
|
|
590
|
+
case "TodoWrite":
|
|
591
|
+
return { summary: "Updated the plan" };
|
|
592
|
+
case "Skill":
|
|
593
|
+
return { summary: `Loaded skill ${String(input.skill ?? input.name ?? "")}` };
|
|
594
|
+
default:
|
|
595
|
+
if (name.startsWith("mcp__agentcut__")) {
|
|
596
|
+
return { summary: name.replace("mcp__agentcut__agentcut_", "").replace(/_/g, " ") };
|
|
597
|
+
}
|
|
598
|
+
return { summary: name };
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
appendText(turn, text) {
|
|
602
|
+
const parts = (turn.message.parts ??= []);
|
|
603
|
+
const last = parts[parts.length - 1];
|
|
604
|
+
if (last && last.type === "text")
|
|
605
|
+
last.text += text;
|
|
606
|
+
else
|
|
607
|
+
parts.push({ type: "text", text });
|
|
608
|
+
}
|
|
609
|
+
/** Apply one agent event to the running turn: chat parts, session, result. */
|
|
610
|
+
handleEvent(turn, event) {
|
|
611
|
+
const { slug } = turn;
|
|
612
|
+
const parts = (turn.message.parts ??= []);
|
|
613
|
+
switch (event.type) {
|
|
614
|
+
case "session":
|
|
615
|
+
this.saveSession(slug, turn.agent.id, event.sessionId);
|
|
616
|
+
return;
|
|
617
|
+
case "message-start": {
|
|
618
|
+
// Separate consecutive assistant messages with a paragraph break.
|
|
619
|
+
const last = parts[parts.length - 1];
|
|
620
|
+
if (last && last.type === "text" && last.text && !last.text.endsWith("\n\n"))
|
|
621
|
+
last.text += "\n\n";
|
|
622
|
+
this.upsertMessage(slug, turn.message);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
case "text":
|
|
626
|
+
this.appendText(turn, event.text);
|
|
627
|
+
this.deps.emit("studio.chat", { slug, kind: "text", messageId: turn.message.id, text: event.text });
|
|
628
|
+
return;
|
|
629
|
+
case "tool-start": {
|
|
630
|
+
if (parts.some((part) => part.type === "tool" && part.id === event.id))
|
|
631
|
+
return;
|
|
632
|
+
const { summary, file } = this.toolSummary(slug, event.name, event.input);
|
|
633
|
+
const part = { type: "tool", id: event.id, name: event.name, summary, file, status: "running" };
|
|
634
|
+
parts.push(part);
|
|
635
|
+
this.deps.emit("studio.chat", { slug, kind: "tool", messageId: turn.message.id, part });
|
|
636
|
+
this.upsertMessage(slug, turn.message);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
case "tool-end": {
|
|
640
|
+
const part = parts.find((candidate) => candidate.type === "tool" && candidate.id === event.id);
|
|
641
|
+
if (!part || part.type !== "tool")
|
|
642
|
+
return;
|
|
643
|
+
part.status = event.ok ? "done" : "error";
|
|
644
|
+
if (event.ok) {
|
|
645
|
+
const images = this.imagesFor(slug, part, event.content);
|
|
646
|
+
if (images.length > 0)
|
|
647
|
+
part.images = images;
|
|
648
|
+
}
|
|
649
|
+
else {
|
|
650
|
+
part.error = event.error?.slice(0, 400);
|
|
651
|
+
}
|
|
652
|
+
this.deps.emit("studio.chat", { slug, kind: "tool_result", messageId: turn.message.id, part });
|
|
653
|
+
if (FILE_TOOLS.has(part.name) && part.status === "done") {
|
|
654
|
+
this.deps.emit("studio.chat", { slug, kind: "file", messageId: turn.message.id, file: part.file });
|
|
655
|
+
}
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
case "error":
|
|
659
|
+
turn.lastError = event.message.slice(0, 1200);
|
|
660
|
+
return;
|
|
661
|
+
case "result": {
|
|
662
|
+
turn.gotResult = true;
|
|
663
|
+
turn.message.status = event.ok ? "done" : "error";
|
|
664
|
+
if (!event.ok)
|
|
665
|
+
turn.message.error = event.error ?? turn.lastError ?? `${turn.agent.name} stopped.`;
|
|
666
|
+
if (event.costUsd !== undefined)
|
|
667
|
+
turn.message.costUsd = event.costUsd;
|
|
668
|
+
turn.message.durationMs = event.durationMs ?? Date.now() - turn.startedAt;
|
|
669
|
+
if (event.sessionId)
|
|
670
|
+
this.saveSession(slug, turn.agent.id, event.sessionId);
|
|
671
|
+
// If nothing was streamed (very short answers), fall back to the final text.
|
|
672
|
+
const hasText = parts.some((part) => part.type === "text" && part.text.trim());
|
|
673
|
+
if (!hasText && event.ok && event.text?.trim())
|
|
674
|
+
this.appendText(turn, event.text);
|
|
675
|
+
this.upsertMessage(slug, turn.message);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
//# sourceMappingURL=chat.js.map
|