@ai-ecoverse/slicc-agent 3.17.0 → 3.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -2
- package/bin/agent +1 -1
- package/dist/agents.js +8 -5
- package/dist/agents.js.map +2 -2
- package/dist/client.js +3 -1
- package/dist/client.js.map +2 -2
- package/dist/control.js +17 -1
- package/dist/control.js.map +2 -2
- package/dist/freezer/index.js +272 -0
- package/dist/freezer/index.js.map +7 -0
- package/dist/freezer/title.js +40 -0
- package/dist/freezer/title.js.map +7 -0
- package/dist/gelatiere/index.js +1 -1
- package/dist/gelatiere/index.js.map +2 -2
- package/dist/host.js +5 -2
- package/dist/host.js.map +2 -2
- package/dist/licks/licks.js +20 -1
- package/dist/licks/licks.js.map +2 -2
- package/dist/main.js +13 -1
- package/dist/main.js.map +2 -2
- package/dist/memory/extract.js +2 -2
- package/dist/memory/extract.js.map +2 -2
- package/dist/memory/index.js +1 -0
- package/dist/memory/index.js.map +2 -2
- package/dist/scoops/cli.js +18 -5
- package/dist/scoops/cli.js.map +2 -2
- package/dist/scoops/index.js +3 -2
- package/dist/scoops/index.js.map +2 -2
- package/dist/scoops/requests.js +1 -1
- package/dist/scoops/requests.js.map +2 -2
- package/dist/services.js.map +2 -2
- package/dist/spectrum/agent-port.js +48 -7
- package/dist/spectrum/agent-port.js.map +2 -2
- package/dist/spectrum/index.js +1 -1
- package/dist/spectrum/index.js.map +2 -2
- package/dist/sprinkles/index.js +15 -6
- package/dist/sprinkles/index.js.map +2 -2
- package/dist/types/agents.d.ts +14 -0
- package/dist/types/client.d.ts +2 -0
- package/dist/types/control.d.ts +2 -1
- package/dist/types/freezer/index.d.ts +49 -0
- package/dist/types/freezer/title.d.ts +6 -0
- package/dist/types/host.d.ts +2 -0
- package/dist/types/licks/licks.d.ts +7 -0
- package/dist/types/memory/extract.d.ts +1 -1
- package/dist/types/memory/index.d.ts +1 -0
- package/dist/types/scoops/cli.d.ts +3 -1
- package/dist/types/scoops/index.d.ts +1 -0
- package/dist/types/scoops/requests.d.ts +1 -1
- package/dist/types/services.d.ts +6 -0
- package/dist/types/spectrum/agent-port.d.ts +8 -4
- package/dist/types/spectrum/index.d.ts +3 -2
- package/dist/types/sprinkles/index.d.ts +2 -1
- package/package.json +3 -3
- package/packages/vfs-root/gelatiere/GELATIERE.md +1 -0
package/README.md
CHANGED
|
@@ -208,9 +208,8 @@ The worker watches the roots and reloads on change. A `skills` prompt section, g
|
|
|
208
208
|
- **Templates:** `/parallel-review` and `/review-loop`, from [pi-subagents](https://github.com/nicobailon/pi-subagents) (MIT). Their wording is kept, and they're rewritten to use `agent --async --agent reviewer|worker`, `agent wait --notify`, `agent send` and `agent stop` instead of pi-subagents' `subagent` tool. The parts that need workflow scripts or forked contexts are left out.
|
|
209
209
|
|
|
210
210
|
**v6 skills.** None of the 29 skills SLICC v6 ships runs here unchanged. They name v6 paths (`/shared`, `/workspace`) or commands this kernel doesn't have. By what they wait for:
|
|
211
|
-
- **Rewritten here:** `delegation` (now the `agent` skill), `automation` (now `licks`), `skill-authoring`, `sprinkles` and `
|
|
211
|
+
- **Rewritten here:** `delegation` (now the `agent` skill), `automation` (now `licks`), `skill-authoring`, `sprinkles`, `welcome` and `transcript-export` (now `freezer show`).
|
|
212
212
|
- **Memory:** `memory` is rewritten here (below); its `status`, `log`, `curate` and `dream` and the curation ledger are not ported. `gelatiere` is rewritten here (below), without `use-cases` and the www.sliccy.com catalog; `wiki` needs its `wiki` CLI.
|
|
213
|
-
- **The freezer (PR 15):** `transcript-export`.
|
|
214
213
|
- **The tray hub, upskill or the Install/Update panel:** `upgrade` (`upgrade apply`, bios#70), `handoff`, `slicc`, `ssh`, `cherry`.
|
|
215
214
|
- **A browser and CDP:** `playwright-cli`, `computer`, `v86`.
|
|
216
215
|
- **v6's JS realm, `.jsh` and `ipk` (slicc-kernel#68):** `jshd`, `mcp`, `workflows`, `package-execution`, `biome`, `ffmpeg`.
|
|
@@ -270,6 +269,27 @@ The `memory` section, read before every request, holds the first 200 lines (at m
|
|
|
270
269
|
|
|
271
270
|
**The panel.** The transcript service adds `memories` and `memoryScopes`, and `AgentControl` `memorySave` and `memoryRemove`; `createAgentModel()` returns a `MemoryAdapter` for spectrum's `MemoryPort`, with `scopes()` (global, cones, roles) for its picker. `memory show [<scope>]` and `memory scopes` in bash print the same files, and the built-in `memory` skill teaches all of it.
|
|
272
271
|
|
|
272
|
+
### The freezer
|
|
273
|
+
|
|
274
|
+
pi durable keeps every conversation and entry in the session database, and has no archive flag and no delete. So freezing is bookkeeping in the `slicc.agents` registry.
|
|
275
|
+
|
|
276
|
+
- **Freeze a cone** (the Freezer's button, or `freeze` in the command palette):
|
|
277
|
+
- its run and its scoops' runs stop;
|
|
278
|
+
- it moves from `cones` to `frozen` (`frozen-<n>`, with its name, conversation, title, model, message count and time), and its live scoops are marked frozen, keeping their transcripts and their workspaces;
|
|
279
|
+
- if it was active, another cone is selected, and if it was the last one, a fresh cone takes its name.
|
|
280
|
+
- Before it moves, 14b's memory extraction is scheduled for anything new.
|
|
281
|
+
- Its title starts as the first user line, then one background call (with `memory.extractModel` or the cone's model) replaces it with a short title.
|
|
282
|
+
- **New chat** (spectrum's `clear`) archives the chat the same way, when it isn't empty, and gives the cone a fresh conversation with the same configuration; its scoops stay. `createAgentModel(connection, { newChat: 'reset' })` makes it a plain reset instead.
|
|
283
|
+
- **Thaw** puts a frozen cone back under its old id when that's free (otherwise a new `cone-<n>`, with a number added to a name that's taken), unfreezes its scoops idle with their workspaces, and selects it. It continues where it stopped.
|
|
284
|
+
- **Delete** removes the frozen entry, marks its scoops gone and deletes their folders. The history stays in the session database, which SLICC can't remove from.
|
|
285
|
+
- **While frozen:**
|
|
286
|
+
- its scoops aren't listed, and `agent send|wait|stop` on one says it is frozen with its cone;
|
|
287
|
+
- cron fires, watches and webhooks aimed at the cone or its scoops are skipped, and the active cone gets one `warn` lick per source naming what was skipped;
|
|
288
|
+
- sprinkles it owned send to the active cone;
|
|
289
|
+
- it can't be rewound.
|
|
290
|
+
- **The `freezer` command** is the same script as `agent`: `freezer list`, `freezer show <id>` (the chat as Markdown, which replaces v6's `transcript-export`) and `freezer thaw <id>`. The gelatiere's pass reads frozen chats with it.
|
|
291
|
+
- **The panel:** the transcript service adds `frozen`, and `AgentControl` adds `freeze`, `newChat`, `thaw` and `discard`.
|
|
292
|
+
|
|
273
293
|
### Sprinkles
|
|
274
294
|
|
|
275
295
|
A sprinkle is a small HTML panel next to the chat. pi has nothing for this; it's SLICC's UI, rendered by slicc-spectrum (≥ 1.23) through its `SprinklePort`.
|
package/bin/agent
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/bin/bash
|
|
2
2
|
dir=/var/lib/slicc/agent/requests
|
|
3
3
|
as=$(basename "$0")
|
|
4
|
-
case "$as" in subagent|sprinkle|memory|gelatiere) ;; *) as=agent ;; esac
|
|
4
|
+
case "$as" in subagent|sprinkle|memory|gelatiere|freezer) ;; *) as=agent ;; esac
|
|
5
5
|
mkdir -p "$dir/in" "$dir/out" 2>/dev/null
|
|
6
6
|
|
|
7
7
|
submit() {
|
package/dist/agents.js
CHANGED
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import { ConeDoc } from "./cone.js";
|
|
5
5
|
const FIRST_CONE = "cone";
|
|
6
6
|
function live(record) {
|
|
7
|
-
return record.dropped === null && !record.gone;
|
|
7
|
+
return record.dropped === null && !record.gone && !record.frozen;
|
|
8
8
|
}
|
|
9
9
|
const AgentsDoc = defineDoc({
|
|
10
10
|
kind: "slicc.agents",
|
|
@@ -100,13 +100,16 @@ async function openAgents(harness, root, context) {
|
|
|
100
100
|
return id;
|
|
101
101
|
}, using);
|
|
102
102
|
},
|
|
103
|
-
|
|
103
|
+
switchCone(conversation, using) {
|
|
104
|
+
return agents.setConversation(state.active, conversation, using);
|
|
105
|
+
},
|
|
106
|
+
async setConversation(coneId, conversation, using) {
|
|
104
107
|
handles.set(conversation.id, conversation);
|
|
105
108
|
await update(async (tx, doc) => {
|
|
106
|
-
doc.cones[
|
|
107
|
-
(await tx.doc(ConeDoc)).conversation = conversation.id;
|
|
109
|
+
doc.cones[coneId].conversation = conversation.id;
|
|
110
|
+
if (coneId === doc.active) (await tx.doc(ConeDoc)).conversation = conversation.id;
|
|
108
111
|
}, using);
|
|
109
|
-
await notifyCone(conversation);
|
|
112
|
+
if (coneId === state.active) await notifyCone(conversation);
|
|
110
113
|
},
|
|
111
114
|
update,
|
|
112
115
|
onChange(listener) {
|
package/dist/agents.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/agents.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport {\n type Conversation,\n type ConversationId,\n defineDoc,\n type Harness,\n type Tx,\n} from '@earendil-works/pi-durable';\nimport { ConeDoc } from './cone.ts';\nimport type { RoleMemory } from './memory/store.ts';\n\nexport const FIRST_CONE = 'cone';\n\nexport type ConeRecord = { name: string; conversation: number };\n\nexport type Mark = { in: number; at: number };\n\nexport type ScoopRecord = {\n name: string;\n folder: string;\n cone: string;\n conversation: number;\n anchor: number;\n role: string | null;\n memory?: RoleMemory;\n origin?: string;\n context?: { project: boolean; global: boolean };\n kind: 'async' | 'sync';\n parent: string;\n depth: number;\n roots: { write: string[]; read: string[] } | null;\n created: Mark | null;\n dropped: Mark | null;\n gone: boolean;\n};\n\nexport function live(record: ScoopRecord): boolean {\n return record.dropped === null && !record.gone;\n}\n\nexport type AgentsState = {\n cones: Record<string, ConeRecord>;\n active: string;\n next: number;\n scoops: Record<string, ScoopRecord>;\n};\n\nexport const AgentsDoc = defineDoc<AgentsState>({\n kind: 'slicc.agents',\n version: 1,\n scope: 'session',\n initial: () => ({ cones: {}, active: FIRST_CONE, next: 2, scoops: {} }),\n});\n\nexport const SCOOP_PREFIX = 'scoop:';\n\nexport function scoopId(folder: string): string {\n return `${SCOOP_PREFIX}${folder}`;\n}\n\nexport function slug(name: string): string {\n const cleaned = name\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^[-._]+|[-._]+$/g, '')\n .slice(0, 48);\n return cleaned || 'scoop';\n}\n\nexport function freeFolder(state: Pick<AgentsState, 'scoops'>, name: string): string {\n const base = slug(name);\n if (!state.scoops[scoopId(base)]) return base;\n for (let n = 2; ; n++) if (!state.scoops[scoopId(`${base}-${n}`)]) return `${base}-${n}`;\n}\n\nexport interface Agents {\n state(): Readonly<AgentsState>;\n cone(): Conversation;\n activeCone(): string;\n conversation(agentId: string, context: Context): Promise<Conversation | undefined>;\n selectCone(id: string, context: Context): Promise<void>;\n createCone(name: string, context: Context): Promise<string>;\n switchCone(conversation: Conversation, context: Context): Promise<void>;\n update<T>(change: (tx: Tx, state: AgentsState) => T | Promise<T>, context: Context): Promise<T>;\n onChange(listener: (state: Readonly<AgentsState>) => void): () => void;\n onCone(listener: (conversation: Conversation) => void | Promise<void>): () => void;\n}\n\nasync function initial(harness: Harness, root: Conversation, context: Context) {\n return harness.commit(async (tx) => {\n const doc = await tx.doc(AgentsDoc);\n if (!doc.cones[FIRST_CONE]) {\n const legacy = (await tx.doc(ConeDoc)).conversation;\n doc.cones[FIRST_CONE] = { name: 'sliccy', conversation: legacy ?? root.id };\n }\n if (!doc.cones[doc.active]) doc.active = FIRST_CONE;\n return JSON.parse(JSON.stringify(doc)) as AgentsState;\n }, context);\n}\n\nexport async function openAgents(\n harness: Harness,\n root: Conversation,\n context: Context\n): Promise<Agents> {\n let state = await initial(harness, root, context);\n const handles = new Map<number, Conversation>([[root.id, root]]);\n const handle = async (id: number, using: Context) => {\n const known = handles.get(id);\n if (known) return known;\n const found = await harness.conversation(id as ConversationId, using);\n if (found) handles.set(id, found);\n return found;\n };\n let cone =\n (await handle((state.cones[state.active] as ConeRecord).conversation, context)) ?? root;\n const changes = new Set<(state: Readonly<AgentsState>) => void>();\n const cones = new Set<(conversation: Conversation) => void | Promise<void>>();\n const notifyCone = async (next: Conversation) => {\n cone = next;\n await Promise.all([...cones].map((listener) => listener(next)));\n };\n const update: Agents['update'] = async (change, using) => {\n const [result, next] = await harness.commit(async (tx) => {\n const doc = await tx.doc(AgentsDoc);\n const value = await change(tx, doc as AgentsState);\n return [value, JSON.parse(JSON.stringify(doc)) as AgentsState] as const;\n }, using);\n state = next;\n for (const listener of changes) listener(state);\n return result;\n };\n const agents: Agents = {\n state: () => state,\n cone: () => cone,\n activeCone: () => state.active,\n async conversation(agentId, using) {\n const id = state.cones[agentId]?.conversation ?? state.scoops[agentId]?.conversation;\n return id === undefined ? undefined : handle(id, using);\n },\n async selectCone(id, using) {\n const record = state.cones[id];\n if (!record) throw new Error(`no cone ${id}`);\n if (state.active === id) return;\n await update((_tx, doc) => {\n doc.active = id;\n }, using);\n await notifyCone((await handle(record.conversation, using)) as Conversation);\n },\n async createCone(name, using) {\n const wanted = name.trim();\n if (!wanted) throw new Error('A cone needs a name.');\n if (Object.values(state.cones).some((record) => record.name === wanted))\n throw new Error(`A cone named ${wanted} already exists.`);\n const conversation = await harness.createConversation(\n {\n ownership: { kind: 'ownerless' },\n agent: { model: (await cone.agent(using)).model ?? null },\n },\n using\n );\n handles.set(conversation.id, conversation);\n return update((_tx, doc) => {\n const id = `cone-${doc.next}`;\n doc.next += 1;\n doc.cones[id] = { name: wanted, conversation: conversation.id };\n return id;\n }, using);\n },\n async
|
|
5
|
-
"mappings": "AACA;AAAA,EAGE;AAAA,OAGK;AACP,SAAS,eAAe;AAGjB,MAAM,aAAa;
|
|
4
|
+
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport {\n type Conversation,\n type ConversationId,\n defineDoc,\n type Harness,\n type Tx,\n} from '@earendil-works/pi-durable';\nimport { ConeDoc } from './cone.ts';\nimport type { RoleMemory } from './memory/store.ts';\n\nexport const FIRST_CONE = 'cone';\n\nexport type ConeRecord = { name: string; conversation: number };\n\nexport type Mark = { in: number; at: number };\n\nexport type ScoopRecord = {\n name: string;\n folder: string;\n cone: string;\n conversation: number;\n anchor: number;\n role: string | null;\n memory?: RoleMemory;\n origin?: string;\n context?: { project: boolean; global: boolean };\n kind: 'async' | 'sync';\n parent: string;\n depth: number;\n roots: { write: string[]; read: string[] } | null;\n created: Mark | null;\n dropped: Mark | null;\n gone: boolean;\n frozen?: string;\n};\n\nexport type FrozenRecord = {\n cone: string;\n name: string;\n conversation: number;\n title: string;\n model: string;\n messages: number;\n frozenAt: number;\n scoops: string[];\n};\n\nexport function live(record: ScoopRecord): boolean {\n return record.dropped === null && !record.gone && !record.frozen;\n}\n\nexport type AgentsState = {\n cones: Record<string, ConeRecord>;\n active: string;\n next: number;\n scoops: Record<string, ScoopRecord>;\n frozen?: Record<string, FrozenRecord>;\n frozenNext?: number;\n};\n\nexport const AgentsDoc = defineDoc<AgentsState>({\n kind: 'slicc.agents',\n version: 1,\n scope: 'session',\n initial: () => ({ cones: {}, active: FIRST_CONE, next: 2, scoops: {} }),\n});\n\nexport const SCOOP_PREFIX = 'scoop:';\n\nexport function scoopId(folder: string): string {\n return `${SCOOP_PREFIX}${folder}`;\n}\n\nexport function slug(name: string): string {\n const cleaned = name\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^[-._]+|[-._]+$/g, '')\n .slice(0, 48);\n return cleaned || 'scoop';\n}\n\nexport function freeFolder(state: Pick<AgentsState, 'scoops'>, name: string): string {\n const base = slug(name);\n if (!state.scoops[scoopId(base)]) return base;\n for (let n = 2; ; n++) if (!state.scoops[scoopId(`${base}-${n}`)]) return `${base}-${n}`;\n}\n\nexport interface Agents {\n state(): Readonly<AgentsState>;\n cone(): Conversation;\n activeCone(): string;\n conversation(agentId: string, context: Context): Promise<Conversation | undefined>;\n selectCone(id: string, context: Context): Promise<void>;\n createCone(name: string, context: Context): Promise<string>;\n switchCone(conversation: Conversation, context: Context): Promise<void>;\n setConversation(coneId: string, conversation: Conversation, context: Context): Promise<void>;\n update<T>(change: (tx: Tx, state: AgentsState) => T | Promise<T>, context: Context): Promise<T>;\n onChange(listener: (state: Readonly<AgentsState>) => void): () => void;\n onCone(listener: (conversation: Conversation) => void | Promise<void>): () => void;\n}\n\nasync function initial(harness: Harness, root: Conversation, context: Context) {\n return harness.commit(async (tx) => {\n const doc = await tx.doc(AgentsDoc);\n if (!doc.cones[FIRST_CONE]) {\n const legacy = (await tx.doc(ConeDoc)).conversation;\n doc.cones[FIRST_CONE] = { name: 'sliccy', conversation: legacy ?? root.id };\n }\n if (!doc.cones[doc.active]) doc.active = FIRST_CONE;\n return JSON.parse(JSON.stringify(doc)) as AgentsState;\n }, context);\n}\n\nexport async function openAgents(\n harness: Harness,\n root: Conversation,\n context: Context\n): Promise<Agents> {\n let state = await initial(harness, root, context);\n const handles = new Map<number, Conversation>([[root.id, root]]);\n const handle = async (id: number, using: Context) => {\n const known = handles.get(id);\n if (known) return known;\n const found = await harness.conversation(id as ConversationId, using);\n if (found) handles.set(id, found);\n return found;\n };\n let cone =\n (await handle((state.cones[state.active] as ConeRecord).conversation, context)) ?? root;\n const changes = new Set<(state: Readonly<AgentsState>) => void>();\n const cones = new Set<(conversation: Conversation) => void | Promise<void>>();\n const notifyCone = async (next: Conversation) => {\n cone = next;\n await Promise.all([...cones].map((listener) => listener(next)));\n };\n const update: Agents['update'] = async (change, using) => {\n const [result, next] = await harness.commit(async (tx) => {\n const doc = await tx.doc(AgentsDoc);\n const value = await change(tx, doc as AgentsState);\n return [value, JSON.parse(JSON.stringify(doc)) as AgentsState] as const;\n }, using);\n state = next;\n for (const listener of changes) listener(state);\n return result;\n };\n const agents: Agents = {\n state: () => state,\n cone: () => cone,\n activeCone: () => state.active,\n async conversation(agentId, using) {\n const id = state.cones[agentId]?.conversation ?? state.scoops[agentId]?.conversation;\n return id === undefined ? undefined : handle(id, using);\n },\n async selectCone(id, using) {\n const record = state.cones[id];\n if (!record) throw new Error(`no cone ${id}`);\n if (state.active === id) return;\n await update((_tx, doc) => {\n doc.active = id;\n }, using);\n await notifyCone((await handle(record.conversation, using)) as Conversation);\n },\n async createCone(name, using) {\n const wanted = name.trim();\n if (!wanted) throw new Error('A cone needs a name.');\n if (Object.values(state.cones).some((record) => record.name === wanted))\n throw new Error(`A cone named ${wanted} already exists.`);\n const conversation = await harness.createConversation(\n {\n ownership: { kind: 'ownerless' },\n agent: { model: (await cone.agent(using)).model ?? null },\n },\n using\n );\n handles.set(conversation.id, conversation);\n return update((_tx, doc) => {\n const id = `cone-${doc.next}`;\n doc.next += 1;\n doc.cones[id] = { name: wanted, conversation: conversation.id };\n return id;\n }, using);\n },\n switchCone(conversation, using) {\n return agents.setConversation(state.active, conversation, using);\n },\n async setConversation(coneId, conversation, using) {\n handles.set(conversation.id, conversation);\n await update(async (tx, doc) => {\n (doc.cones[coneId] as ConeRecord).conversation = conversation.id;\n if (coneId === doc.active) (await tx.doc(ConeDoc)).conversation = conversation.id;\n }, using);\n if (coneId === state.active) await notifyCone(conversation);\n },\n update,\n onChange(listener) {\n changes.add(listener);\n return () => changes.delete(listener);\n },\n onCone(listener) {\n cones.add(listener);\n return () => cones.delete(listener);\n },\n };\n return agents;\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EAGE;AAAA,OAGK;AACP,SAAS,eAAe;AAGjB,MAAM,aAAa;AAqCnB,SAAS,KAAK,QAA8B;AACjD,SAAO,OAAO,YAAY,QAAQ,CAAC,OAAO,QAAQ,CAAC,OAAO;AAC5D;AAWO,MAAM,YAAY,UAAuB;AAAA,EAC9C,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,SAAS,OAAO,EAAE,OAAO,CAAC,GAAG,QAAQ,YAAY,MAAM,GAAG,QAAQ,CAAC,EAAE;AACvE,CAAC;AAEM,MAAM,eAAe;AAErB,SAAS,QAAQ,QAAwB;AAC9C,SAAO,GAAG,YAAY,GAAG,MAAM;AACjC;AAEO,SAAS,KAAK,MAAsB;AACzC,QAAM,UAAU,KACb,YAAY,EACZ,QAAQ,k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Q;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/client.js
CHANGED
|
@@ -46,7 +46,8 @@ async function connectAgent(endpoint, options = {}) {
|
|
|
46
46
|
commands,
|
|
47
47
|
sprinkles,
|
|
48
48
|
memories,
|
|
49
|
-
memoryScopes
|
|
49
|
+
memoryScopes,
|
|
50
|
+
frozen
|
|
50
51
|
} = session.use(AgentTranscript);
|
|
51
52
|
const settings = session.use(AgentSettings);
|
|
52
53
|
await session.ready(context);
|
|
@@ -61,6 +62,7 @@ async function connectAgent(endpoint, options = {}) {
|
|
|
61
62
|
sprinkles,
|
|
62
63
|
memories,
|
|
63
64
|
memoryScopes,
|
|
65
|
+
frozen,
|
|
64
66
|
settings,
|
|
65
67
|
async prompt(text, whenBusy = "followUp") {
|
|
66
68
|
const sent = await control.send({ text, whenBusy, requestId: null }, context);
|
package/dist/client.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type Context,\n createRemoteServiceBinding,\n type ReplicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport { Client, createClientServiceTransport } from '@earendil-works/pi-client';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { MemoryEntry, MemoryScope } from './memory/format.ts';\nimport {\n AGENT_SESSION,\n AgentControl,\n AgentSessions,\n AgentSettings,\n type AgentsSummary,\n AgentTranscript,\n type Command,\n type Delivered,\n type SendMode,\n} from './services.ts';\nimport type { Sprinkle } from './sprinkles/kind.ts';\nimport { PortChannel, type PortEndpoint } from './wire.ts';\n\nexport interface AgentConnection {\n readonly serverId: string;\n readonly control: AgentControl;\n readonly transcript: ReplicatedState<ConversationView>;\n readonly deliveries: ReplicatedState<Record<string, Delivered>>;\n readonly agents?: ReplicatedState<AgentsSummary>;\n readonly views?: ReplicatedState<Record<string, ConversationView>>;\n readonly commands?: ReplicatedState<Command[]>;\n readonly sprinkles?: ReplicatedState<Sprinkle[]>;\n readonly memories?: ReplicatedState<MemoryEntry[]>;\n readonly memoryScopes?: ReplicatedState<MemoryScope[]>;\n readonly settings: AgentSettings;\n prompt(text: string, whenBusy?: SendMode): Promise<string>;\n close(): Promise<void>;\n}\n\nfunction attached(client: Client): Promise<void> {\n return new Promise((resolve) => {\n const stop = client.onAttachmentChange(() => {\n stop();\n resolve();\n });\n });\n}\n\nexport async function connectAgent(\n endpoint: PortEndpoint,\n options: { context?: Context } = {}\n): Promise<AgentConnection> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const channel = new PortChannel(endpoint);\n const serverId = await channel.hello;\n const client = await Client.connect({ serverId, transportFactory: channel.transport });\n const server = createRemoteServiceBinding({\n services: [AgentSessions],\n transport: createClientServiceTransport(client, () => ({ serverId })),\n bound: true,\n });\n const ready = attached(client);\n await server.use(AgentSessions).attach(AGENT_SESSION, context);\n await ready;\n const session = createRemoteServiceBinding({\n services: [AgentControl, AgentTranscript, AgentSettings],\n transport: createClientServiceTransport(client, () => client.attachment),\n bound: true,\n });\n const control = session.use(AgentControl);\n const {\n state: transcript,\n deliveries,\n agents,\n views,\n commands,\n sprinkles,\n memories,\n memoryScopes,\n } = session.use(AgentTranscript);\n const settings = session.use(AgentSettings);\n await session.ready(context);\n return {\n serverId,\n control,\n transcript,\n deliveries,\n agents,\n views,\n commands,\n sprinkles,\n memories,\n memoryScopes,\n settings,\n async prompt(text, whenBusy = 'followUp') {\n const sent = await control.send({ text, whenBusy, requestId: null }, context);\n if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);\n const settled = await control.wait(sent.submissionId, context);\n if (settled.status !== 'done') throw new Error(`unanswered: ${settled.reason}`);\n return settled.text;\n },\n async close() {\n await server.use(AgentSessions).detach(context);\n await session.dispose(context);\n await server.dispose(context);\n await client.dispose();\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,EAEE;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,QAAQ,oCAAoC;
|
|
4
|
+
"sourcesContent": ["import {\n type Context,\n createRemoteServiceBinding,\n type ReplicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport { Client, createClientServiceTransport } from '@earendil-works/pi-client';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { FrozenCone } from './freezer/index.ts';\nimport type { MemoryEntry, MemoryScope } from './memory/format.ts';\nimport {\n AGENT_SESSION,\n AgentControl,\n AgentSessions,\n AgentSettings,\n type AgentsSummary,\n AgentTranscript,\n type Command,\n type Delivered,\n type SendMode,\n} from './services.ts';\nimport type { Sprinkle } from './sprinkles/kind.ts';\nimport { PortChannel, type PortEndpoint } from './wire.ts';\n\nexport interface AgentConnection {\n readonly serverId: string;\n readonly control: AgentControl;\n readonly transcript: ReplicatedState<ConversationView>;\n readonly deliveries: ReplicatedState<Record<string, Delivered>>;\n readonly agents?: ReplicatedState<AgentsSummary>;\n readonly views?: ReplicatedState<Record<string, ConversationView>>;\n readonly commands?: ReplicatedState<Command[]>;\n readonly sprinkles?: ReplicatedState<Sprinkle[]>;\n readonly memories?: ReplicatedState<MemoryEntry[]>;\n readonly memoryScopes?: ReplicatedState<MemoryScope[]>;\n readonly frozen?: ReplicatedState<FrozenCone[]>;\n readonly settings: AgentSettings;\n prompt(text: string, whenBusy?: SendMode): Promise<string>;\n close(): Promise<void>;\n}\n\nfunction attached(client: Client): Promise<void> {\n return new Promise((resolve) => {\n const stop = client.onAttachmentChange(() => {\n stop();\n resolve();\n });\n });\n}\n\nexport async function connectAgent(\n endpoint: PortEndpoint,\n options: { context?: Context } = {}\n): Promise<AgentConnection> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const channel = new PortChannel(endpoint);\n const serverId = await channel.hello;\n const client = await Client.connect({ serverId, transportFactory: channel.transport });\n const server = createRemoteServiceBinding({\n services: [AgentSessions],\n transport: createClientServiceTransport(client, () => ({ serverId })),\n bound: true,\n });\n const ready = attached(client);\n await server.use(AgentSessions).attach(AGENT_SESSION, context);\n await ready;\n const session = createRemoteServiceBinding({\n services: [AgentControl, AgentTranscript, AgentSettings],\n transport: createClientServiceTransport(client, () => client.attachment),\n bound: true,\n });\n const control = session.use(AgentControl);\n const {\n state: transcript,\n deliveries,\n agents,\n views,\n commands,\n sprinkles,\n memories,\n memoryScopes,\n frozen,\n } = session.use(AgentTranscript);\n const settings = session.use(AgentSettings);\n await session.ready(context);\n return {\n serverId,\n control,\n transcript,\n deliveries,\n agents,\n views,\n commands,\n sprinkles,\n memories,\n memoryScopes,\n frozen,\n settings,\n async prompt(text, whenBusy = 'followUp') {\n const sent = await control.send({ text, whenBusy, requestId: null }, context);\n if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);\n const settled = await control.wait(sent.submissionId, context);\n if (settled.status !== 'done') throw new Error(`unanswered: ${settled.reason}`);\n return settled.text;\n },\n async close() {\n await server.use(AgentSessions).detach(context);\n await session.dispose(context);\n await server.dispose(context);\n await client.dispose();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EAEE;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,QAAQ,oCAAoC;AAIrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OAIK;AAEP,SAAS,mBAAsC;AAmB/C,SAAS,SAAS,QAA+B;AAC/C,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,OAAO,OAAO,mBAAmB,MAAM;AAC3C,WAAK;AACL,cAAQ;AAAA,IACV,CAAC;AAAA,EACH,CAAC;AACH;AAEA,eAAsB,aACpB,UACA,UAAiC,CAAC,GACR;AAC1B,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,UAAU,IAAI,YAAY,QAAQ;AACxC,QAAM,WAAW,MAAM,QAAQ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MAAM,EAAE;AAC9E,aAAO,QAAQ;AAAA,IACjB;AAAA,IACA,MAAM,QAAQ;AACZ,YAAM,OAAO,IAAI,aAAa,EAAE,OAAO,OAAO;AAC9C,YAAM,QAAQ,QAAQ,OAAO;AAC7B,YAAM,OAAO,QAAQ,OAAO;AAC5B,YAAM,OAAO,QAAQ;AAAA,IACvB;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/control.js
CHANGED
|
@@ -15,6 +15,21 @@ function created(run) {
|
|
|
15
15
|
(error) => ({ id: null, error: error.message })
|
|
16
16
|
);
|
|
17
17
|
}
|
|
18
|
+
function freezerControl(freezer) {
|
|
19
|
+
const needed = () => {
|
|
20
|
+
if (!freezer) throw new Error("This agent has no freezer.");
|
|
21
|
+
return freezer;
|
|
22
|
+
};
|
|
23
|
+
return {
|
|
24
|
+
freeze: (agentId, context) => created(async () => needed().freeze(agentId, context)),
|
|
25
|
+
newChat: (agentId, context) => created(async () => await needed().newChat(agentId, context) ?? ""),
|
|
26
|
+
thaw: (id, context) => created(async () => needed().thaw(id, context)),
|
|
27
|
+
discard: (id, context) => created(async () => {
|
|
28
|
+
await needed().discard(id, context);
|
|
29
|
+
return id;
|
|
30
|
+
})
|
|
31
|
+
};
|
|
32
|
+
}
|
|
18
33
|
function memoryControl(memory) {
|
|
19
34
|
return {
|
|
20
35
|
async memorySave(draft, context) {
|
|
@@ -122,7 +137,7 @@ async function rewindAgent(deps, agentId, messageId, context) {
|
|
|
122
137
|
else await cone.switchCone(fork, context);
|
|
123
138
|
return { done: true, text: found.turn.text, reason: null };
|
|
124
139
|
}
|
|
125
|
-
function createAgentControl(harness, target, deliveries, licks, scoops, skills, sprinkles, memory) {
|
|
140
|
+
function createAgentControl(harness, target, deliveries, licks, scoops, skills, sprinkles, memory, freezer) {
|
|
126
141
|
const cone = cones(target);
|
|
127
142
|
const current = () => cone.cone();
|
|
128
143
|
const agents = target.agents;
|
|
@@ -183,6 +198,7 @@ function createAgentControl(harness, target, deliveries, licks, scoops, skills,
|
|
|
183
198
|
withdraw: (id, context) => withdraw(current(), id, context),
|
|
184
199
|
...sprinkleControl(sprinkles),
|
|
185
200
|
...memoryControl(memory),
|
|
201
|
+
...freezerControl(freezer),
|
|
186
202
|
async unqueue(agentId, id, context) {
|
|
187
203
|
return withdraw(await conversationFor(agentId, context), id, context);
|
|
188
204
|
},
|
package/dist/control.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/control.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport {\n type AgentChange,\n AssistantEntry,\n type Conversation,\n ConversationBusy,\n type ConversationView,\n type EntryId,\n type EntryRecord,\n type Harness,\n type SubmissionId,\n} from '@earendil-works/pi-durable';\nimport { answerText } from './agent.ts';\nimport type { Agents } from './agents.ts';\nimport type { Cones } from './cone.ts';\nimport type { Deliveries } from './deliveries.ts';\nimport type { LickSources, Licks } from './licks/index.ts';\nimport { LICK_STATE_KIND } from './licks/state.ts';\nimport type { MemoryRuntime } from './memory/index.ts';\nimport type { Scoops, ScoopsRuntime } from './scoops/index.ts';\nimport type { AgentControl, Created, OperationError, Rewound, SendResponse } from './services.ts';\nimport type { SkillsRuntime } from './skills/index.ts';\nimport type { SprinklesRuntime } from './sprinkles/index.ts';\n\nexport interface HostLicks {\n licks: Licks;\n sources: LickSources;\n}\n\nexport interface HostScoops {\n scoops: Scoops;\n runtime: ScoopsRuntime;\n}\n\ntype WithAgents = { agents?: Agents };\n\nexport function readable(out: string): string {\n const text = out.replace(/^(?:sub)?agent: /, '').trim();\n const sentence = text.charAt(0).toUpperCase() + text.slice(1);\n return /[.!?]$/.test(sentence) ? sentence : `${sentence}.`;\n}\n\nfunction created(run: () => Promise<string>): Promise<Created> {\n return run().then(\n (id) => ({ id, error: null }),\n (error: Error) => ({ id: null, error: error.message })\n );\n}\n\nfunction memoryControl(\n memory: Pick<MemoryRuntime, 'save' | 'remove'> | undefined\n): Pick<AgentControl, 'memorySave' | 'memoryRemove'> {\n return {\n async memorySave(draft, context) {\n if (!memory) throw new Error('This agent has no memory.');\n const { id, ...rest } = draft;\n return memory.save({ ...rest, ...(id ? { id } : {}) }, context);\n },\n async memoryRemove(id, context) {\n return { removed: memory ? await memory.remove(id, context) : false };\n },\n };\n}\n\nfunction sprinkleControl(\n sprinkles: Pick<SprinklesRuntime, 'send' | 'call'> | undefined\n): Pick<AgentControl, 'sprinkleSend' | 'sprinkleCall'> {\n return {\n sprinkleSend: async (id, payload, context) =>\n sprinkles ? sprinkles.send(id, payload, context) : { delivered: false },\n async sprinkleCall(id, method, args, context) {\n if (!sprinkles) throw new Error('This agent has no sprinkles.');\n return sprinkles.call(id, method, args, context);\n },\n };\n}\n\nexport function submissionId(value: string): SubmissionId | undefined {\n const id = Number(value);\n return /^[1-9][0-9]*$/.test(value) && Number.isSafeInteger(id) ? (id as SubmissionId) : undefined;\n}\n\nfunction operationError(error: unknown): OperationError {\n if (error instanceof ConversationBusy) return { code: 'busy', message: error.message };\n return { code: 'failed', message: error instanceof Error ? error.message : String(error) };\n}\n\nasync function accepted(operation: () => Promise<{ id: number } | number>): Promise<SendResponse> {\n try {\n const result = await operation();\n const id = typeof result === 'number' ? result : result.id;\n return { accepted: true, submissionId: String(id), error: null };\n } catch (error) {\n return { accepted: false, submissionId: null, error: operationError(error) };\n }\n}\n\nfunction cones(target: Conversation | Cones): Cones {\n if ('cone' in target) return target;\n return {\n cone: () => target,\n switchCone: async () => {\n throw new Error('this conversation has no cone to rewind');\n },\n };\n}\n\ninterface Turn {\n text: string;\n at: EntryId | null;\n}\n\nfunction lastTurn(view: ConversationView, messageId: string | null): Turn | null {\n const { entries } = view;\n const target = entries.findIndex((entry) => `e${entry.id}` === messageId);\n if (target < 0) return null;\n const turn = entries.slice(0, target).findLastIndex((entry) => entry.kind === 'pi.user');\n if (turn < 0) return null;\n const user = entries[turn] as EntryRecord;\n return { text: answerText(user.model?.[0]?.content), at: entries[turn - 1]?.id ?? null };\n}\n\nfunction busy(view: ConversationView): boolean {\n const live = view.docs['pi.live'] as { run?: unknown } | undefined;\n const inbox = view.docs['pi.inbox'] as { items?: unknown[] } | undefined;\n return Boolean(live?.run) || Boolean(inbox?.items?.length);\n}\n\ntype RewindDeps = { harness: Harness; agents?: Agents; cone: Cones; scoops?: HostScoops };\n\nasync function turnIn(\n harness: Harness,\n conversation: Conversation,\n messageId: string | null,\n context: Context\n): Promise<{ turn: Turn; view: ConversationView } | Rewound> {\n const attached = await conversation.viewState(context);\n const view = attached.value;\n attached.dispose();\n const pending = (await harness.inspect(context)).submissions.some(\n (submission) => submission.conversationId === conversation.id\n );\n if (pending || busy(view)) return { done: false, text: null, reason: 'busy' };\n const turn = lastTurn(view, messageId);\n return turn ? { turn, view } : { done: false, text: null, reason: 'no-turn' };\n}\n\nasync function forkAt(\n harness: Harness,\n conversation: Conversation,\n found: { turn: Turn },\n context: Context\n): Promise<Conversation> {\n const ownership = { kind: 'ownerless' } as const;\n if (found.turn.at !== null) return conversation.fork(found.turn.at, { ownership }, context);\n const agent = await conversation.agent(context);\n const change: AgentChange = {\n model: agent.model ?? null,\n thinkingLevel: agent.thinkingLevel,\n extensions: agent.extensions,\n tools: agent.tools,\n instructions: agent.instructions ?? null,\n cwd: agent.cwd ?? null,\n };\n return harness.createConversation({ ownership, agent: change }, context);\n}\n\nasync function rewindAgent(\n deps: RewindDeps,\n agentId: string | null,\n messageId: string | null,\n context: Context\n): Promise<Rewound> {\n const { harness, agents, cone, scoops } = deps;\n const scoop = agentId && agents ? agents.state().scoops[agentId] : undefined;\n if (agentId && agents && !scoop && agentId !== agents.activeCone())\n await agents.selectCone(agentId, context);\n const conversation =\n scoop && agents\n ? ((await agents.conversation(agentId as string, context)) as Conversation)\n : cone.cone();\n const found = await turnIn(harness, conversation, messageId, context);\n if ('reason' in found) return found;\n const fork = await forkAt(harness, conversation, found, context);\n const changed =\n scoops && agents && !scoop\n ? await scoops.scoops.rewound(agents.activeCone(), fork, context)\n : { stopped: [], restored: [] };\n await fork.submit(\n { type: 'write', entry: { kind: 'slicc.rewound', data: { turns: 1, ...changed } } },\n context\n );\n if (scoop && agents)\n await agents.update((_tx, state) => {\n (state.scoops[agentId as string] as { conversation: number }).conversation = fork.id;\n }, context);\n else await cone.switchCone(fork, context);\n return { done: true, text: found.turn.text, reason: null };\n}\n\nexport function createAgentControl(\n harness: Harness,\n target: Conversation | Cones,\n deliveries?: Deliveries,\n licks?: HostLicks,\n scoops?: HostScoops,\n skills?: Pick<SkillsRuntime, 'expand'>,\n sprinkles?: Pick<SprinklesRuntime, 'send' | 'call'>,\n memory?: Pick<MemoryRuntime, 'save' | 'remove'>\n): AgentControl {\n const cone = cones(target);\n const current = () => cone.cone();\n const agents = (target as WithAgents).agents;\n const conversationFor = async (agentId: string | null | undefined, context: Context) => {\n if (!agentId || !agents) return current();\n const found = await agents.conversation(agentId, context);\n if (!found) throw new Error(`There is no agent ${agentId}.`);\n return found;\n };\n const withdraw = async (conversation: Conversation, id: string, context: Context) => {\n const parsed = submissionId(id);\n if (parsed === undefined) return { outcome: 'not_found' as const };\n const result = await harness.abortSubmission(parsed, context, conversation.id);\n if (result === 'aborted') return { outcome: 'withdrawn' as const };\n return {\n outcome: result === 'not_found' ? ('not_found' as const) : ('already_placed' as const),\n };\n };\n let lock: Promise<unknown> = Promise.resolve();\n const serial = <T>(operation: () => Promise<T>): Promise<T> => {\n const run = lock.then(operation, operation);\n lock = run.catch(() => undefined);\n return run;\n };\n const rewindIn = (agentId: string | null, messageId: string | null, context: Context) =>\n serial(() => rewindAgent({ harness, agents, cone, scoops }, agentId, messageId, context));\n return {\n send(request, context) {\n return serial(async () => {\n const text = skills ? await skills.expand(request.text, context) : request.text;\n const response = await accepted(async () =>\n (await conversationFor(request.agentId, context)).submit(\n {\n type: 'input',\n content: text,\n whenBusy: request.whenBusy,\n ...(request.requestId ? { requestId: request.requestId } : {}),\n },\n context\n )\n );\n const id = response.submissionId === null ? undefined : submissionId(response.submissionId);\n if (id !== undefined) deliveries?.expect(id, request.whenBusy);\n return response;\n });\n },\n rewind: (messageId, context) => rewindIn(null, messageId, context),\n rewindAgent: (agentId, messageId, context) => rewindIn(agentId, messageId, context),\n\n async wait(id, context) {\n const parsed = submissionId(id);\n const submission =\n parsed === undefined ? undefined : await harness.submission(parsed, context);\n if (!submission) throw new Error(`unknown submission ${id}`);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) return { status: 'unanswered', text: null, reason: String(reason) };\n const entry = await harness.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return { status: 'done', text: answerText(entry?.model?.[0]?.content), reason: null };\n },\n withdraw: (id, context) => withdraw(current(), id, context),\n ...sprinkleControl(sprinkles),\n ...memoryControl(memory),\n async unqueue(agentId, id, context) {\n return withdraw(await conversationFor(agentId, context), id, context);\n },\n abort: (context) => current().abort(context),\n compact: (instructions, context) =>\n accepted(() => current().compact(instructions ?? undefined, context)),\n reset: (handoff, context) => current().reset(handoff ?? undefined, context),\n resolveLick(lickId, state, context) {\n return serial(async () => {\n if (!licks) return { done: false, text: null, error: 'this agent has no licks' };\n const conversation = current();\n const action = state === 'confirmed' ? 'confirm' : 'dismiss';\n try {\n const text = await licks.licks.decide(conversation, lickId, action, undefined, context);\n await conversation.submit(\n {\n type: 'write',\n entry: {\n kind: LICK_STATE_KIND,\n data: { lick: lickId, state, by: 'user' },\n model: [\n {\n role: 'user',\n content: `The user ${state} lick ${lickId}: ${text}`,\n timestamp: Date.now(),\n },\n ],\n },\n },\n context\n );\n return { done: true, text, error: null };\n } catch (error) {\n return { done: false, text: null, error: (error as Error).message };\n }\n });\n },\n async webhook(name, delivery, context) {\n const delivered = licks\n ? await licks.sources.webhook(\n name,\n {\n ...(delivery.id ? { id: delivery.id } : {}),\n headers: delivery.headers,\n body: delivery.body,\n },\n context\n )\n : false;\n return { delivered };\n },\n async stopAgent(agentId, context) {\n await (await conversationFor(agentId, context)).abort(context);\n },\n async selectCone(agentId, context) {\n await agents?.selectCone(agentId, context);\n },\n createCone(name, context) {\n return created(async () => {\n if (!agents) throw new Error('This agent has a single cone.');\n return agents.createCone(name, context);\n });\n },\n createScoop(parentId, name, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const roles = await scoops.runtime.roles(context);\n const answer = await scoops.scoops.spawn(\n { cone: parentId, name, prompts: [], fromAgent: false, limits: roles.limits },\n context\n );\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return `scoop:${answer.out.trim()}`;\n });\n },\n drop(agentId, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const answer = await scoops.scoops.stop(agentId, false, context);\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return agentId;\n });\n },\n configure: async (change, context) =>\n (await conversationFor(change.agentId, context)).configure(\n {\n ...(change.model ? { model: change.model } : {}),\n ...(change.thinkingLevel ? { thinkingLevel: change.thinkingLevel } : {}),\n },\n context\n ),\n };\n}\n"],
|
|
5
|
-
"mappings": "AACA;AAAA,EAEE;AAAA,EAEA;AAAA,OAMK;AACP,SAAS,kBAAkB;
|
|
4
|
+
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport {\n type AgentChange,\n AssistantEntry,\n type Conversation,\n ConversationBusy,\n type ConversationView,\n type EntryId,\n type EntryRecord,\n type Harness,\n type SubmissionId,\n} from '@earendil-works/pi-durable';\nimport { answerText } from './agent.ts';\nimport type { Agents } from './agents.ts';\nimport type { Cones } from './cone.ts';\nimport type { Deliveries } from './deliveries.ts';\nimport type { FreezerRuntime } from './freezer/index.ts';\nimport type { LickSources, Licks } from './licks/index.ts';\nimport { LICK_STATE_KIND } from './licks/state.ts';\nimport type { MemoryRuntime } from './memory/index.ts';\nimport type { Scoops, ScoopsRuntime } from './scoops/index.ts';\nimport type { AgentControl, Created, OperationError, Rewound, SendResponse } from './services.ts';\nimport type { SkillsRuntime } from './skills/index.ts';\nimport type { SprinklesRuntime } from './sprinkles/index.ts';\n\nexport interface HostLicks {\n licks: Licks;\n sources: LickSources;\n}\n\nexport interface HostScoops {\n scoops: Scoops;\n runtime: ScoopsRuntime;\n}\n\ntype WithAgents = { agents?: Agents };\n\nexport function readable(out: string): string {\n const text = out.replace(/^(?:sub)?agent: /, '').trim();\n const sentence = text.charAt(0).toUpperCase() + text.slice(1);\n return /[.!?]$/.test(sentence) ? sentence : `${sentence}.`;\n}\n\nfunction created(run: () => Promise<string>): Promise<Created> {\n return run().then(\n (id) => ({ id, error: null }),\n (error: Error) => ({ id: null, error: error.message })\n );\n}\n\nfunction freezerControl(\n freezer: Pick<FreezerRuntime, 'freeze' | 'newChat' | 'thaw' | 'discard'> | undefined\n): Pick<AgentControl, 'freeze' | 'newChat' | 'thaw' | 'discard'> {\n const needed = () => {\n if (!freezer) throw new Error('This agent has no freezer.');\n return freezer;\n };\n return {\n freeze: (agentId, context) => created(async () => needed().freeze(agentId, context)),\n newChat: (agentId, context) =>\n created(async () => (await needed().newChat(agentId, context)) ?? ''),\n thaw: (id, context) => created(async () => needed().thaw(id, context)),\n discard: (id, context) =>\n created(async () => {\n await needed().discard(id, context);\n return id;\n }),\n };\n}\n\nfunction memoryControl(\n memory: Pick<MemoryRuntime, 'save' | 'remove'> | undefined\n): Pick<AgentControl, 'memorySave' | 'memoryRemove'> {\n return {\n async memorySave(draft, context) {\n if (!memory) throw new Error('This agent has no memory.');\n const { id, ...rest } = draft;\n return memory.save({ ...rest, ...(id ? { id } : {}) }, context);\n },\n async memoryRemove(id, context) {\n return { removed: memory ? await memory.remove(id, context) : false };\n },\n };\n}\n\nfunction sprinkleControl(\n sprinkles: Pick<SprinklesRuntime, 'send' | 'call'> | undefined\n): Pick<AgentControl, 'sprinkleSend' | 'sprinkleCall'> {\n return {\n sprinkleSend: async (id, payload, context) =>\n sprinkles ? sprinkles.send(id, payload, context) : { delivered: false },\n async sprinkleCall(id, method, args, context) {\n if (!sprinkles) throw new Error('This agent has no sprinkles.');\n return sprinkles.call(id, method, args, context);\n },\n };\n}\n\nexport function submissionId(value: string): SubmissionId | undefined {\n const id = Number(value);\n return /^[1-9][0-9]*$/.test(value) && Number.isSafeInteger(id) ? (id as SubmissionId) : undefined;\n}\n\nfunction operationError(error: unknown): OperationError {\n if (error instanceof ConversationBusy) return { code: 'busy', message: error.message };\n return { code: 'failed', message: error instanceof Error ? error.message : String(error) };\n}\n\nasync function accepted(operation: () => Promise<{ id: number } | number>): Promise<SendResponse> {\n try {\n const result = await operation();\n const id = typeof result === 'number' ? result : result.id;\n return { accepted: true, submissionId: String(id), error: null };\n } catch (error) {\n return { accepted: false, submissionId: null, error: operationError(error) };\n }\n}\n\nfunction cones(target: Conversation | Cones): Cones {\n if ('cone' in target) return target;\n return {\n cone: () => target,\n switchCone: async () => {\n throw new Error('this conversation has no cone to rewind');\n },\n };\n}\n\ninterface Turn {\n text: string;\n at: EntryId | null;\n}\n\nfunction lastTurn(view: ConversationView, messageId: string | null): Turn | null {\n const { entries } = view;\n const target = entries.findIndex((entry) => `e${entry.id}` === messageId);\n if (target < 0) return null;\n const turn = entries.slice(0, target).findLastIndex((entry) => entry.kind === 'pi.user');\n if (turn < 0) return null;\n const user = entries[turn] as EntryRecord;\n return { text: answerText(user.model?.[0]?.content), at: entries[turn - 1]?.id ?? null };\n}\n\nfunction busy(view: ConversationView): boolean {\n const live = view.docs['pi.live'] as { run?: unknown } | undefined;\n const inbox = view.docs['pi.inbox'] as { items?: unknown[] } | undefined;\n return Boolean(live?.run) || Boolean(inbox?.items?.length);\n}\n\ntype RewindDeps = { harness: Harness; agents?: Agents; cone: Cones; scoops?: HostScoops };\n\nasync function turnIn(\n harness: Harness,\n conversation: Conversation,\n messageId: string | null,\n context: Context\n): Promise<{ turn: Turn; view: ConversationView } | Rewound> {\n const attached = await conversation.viewState(context);\n const view = attached.value;\n attached.dispose();\n const pending = (await harness.inspect(context)).submissions.some(\n (submission) => submission.conversationId === conversation.id\n );\n if (pending || busy(view)) return { done: false, text: null, reason: 'busy' };\n const turn = lastTurn(view, messageId);\n return turn ? { turn, view } : { done: false, text: null, reason: 'no-turn' };\n}\n\nasync function forkAt(\n harness: Harness,\n conversation: Conversation,\n found: { turn: Turn },\n context: Context\n): Promise<Conversation> {\n const ownership = { kind: 'ownerless' } as const;\n if (found.turn.at !== null) return conversation.fork(found.turn.at, { ownership }, context);\n const agent = await conversation.agent(context);\n const change: AgentChange = {\n model: agent.model ?? null,\n thinkingLevel: agent.thinkingLevel,\n extensions: agent.extensions,\n tools: agent.tools,\n instructions: agent.instructions ?? null,\n cwd: agent.cwd ?? null,\n };\n return harness.createConversation({ ownership, agent: change }, context);\n}\n\nasync function rewindAgent(\n deps: RewindDeps,\n agentId: string | null,\n messageId: string | null,\n context: Context\n): Promise<Rewound> {\n const { harness, agents, cone, scoops } = deps;\n const scoop = agentId && agents ? agents.state().scoops[agentId] : undefined;\n if (agentId && agents && !scoop && agentId !== agents.activeCone())\n await agents.selectCone(agentId, context);\n const conversation =\n scoop && agents\n ? ((await agents.conversation(agentId as string, context)) as Conversation)\n : cone.cone();\n const found = await turnIn(harness, conversation, messageId, context);\n if ('reason' in found) return found;\n const fork = await forkAt(harness, conversation, found, context);\n const changed =\n scoops && agents && !scoop\n ? await scoops.scoops.rewound(agents.activeCone(), fork, context)\n : { stopped: [], restored: [] };\n await fork.submit(\n { type: 'write', entry: { kind: 'slicc.rewound', data: { turns: 1, ...changed } } },\n context\n );\n if (scoop && agents)\n await agents.update((_tx, state) => {\n (state.scoops[agentId as string] as { conversation: number }).conversation = fork.id;\n }, context);\n else await cone.switchCone(fork, context);\n return { done: true, text: found.turn.text, reason: null };\n}\n\nexport function createAgentControl(\n harness: Harness,\n target: Conversation | Cones,\n deliveries?: Deliveries,\n licks?: HostLicks,\n scoops?: HostScoops,\n skills?: Pick<SkillsRuntime, 'expand'>,\n sprinkles?: Pick<SprinklesRuntime, 'send' | 'call'>,\n memory?: Pick<MemoryRuntime, 'save' | 'remove'>,\n freezer?: Pick<FreezerRuntime, 'freeze' | 'newChat' | 'thaw' | 'discard'>\n): AgentControl {\n const cone = cones(target);\n const current = () => cone.cone();\n const agents = (target as WithAgents).agents;\n const conversationFor = async (agentId: string | null | undefined, context: Context) => {\n if (!agentId || !agents) return current();\n const found = await agents.conversation(agentId, context);\n if (!found) throw new Error(`There is no agent ${agentId}.`);\n return found;\n };\n const withdraw = async (conversation: Conversation, id: string, context: Context) => {\n const parsed = submissionId(id);\n if (parsed === undefined) return { outcome: 'not_found' as const };\n const result = await harness.abortSubmission(parsed, context, conversation.id);\n if (result === 'aborted') return { outcome: 'withdrawn' as const };\n return {\n outcome: result === 'not_found' ? ('not_found' as const) : ('already_placed' as const),\n };\n };\n let lock: Promise<unknown> = Promise.resolve();\n const serial = <T>(operation: () => Promise<T>): Promise<T> => {\n const run = lock.then(operation, operation);\n lock = run.catch(() => undefined);\n return run;\n };\n const rewindIn = (agentId: string | null, messageId: string | null, context: Context) =>\n serial(() => rewindAgent({ harness, agents, cone, scoops }, agentId, messageId, context));\n return {\n send(request, context) {\n return serial(async () => {\n const text = skills ? await skills.expand(request.text, context) : request.text;\n const response = await accepted(async () =>\n (await conversationFor(request.agentId, context)).submit(\n {\n type: 'input',\n content: text,\n whenBusy: request.whenBusy,\n ...(request.requestId ? { requestId: request.requestId } : {}),\n },\n context\n )\n );\n const id = response.submissionId === null ? undefined : submissionId(response.submissionId);\n if (id !== undefined) deliveries?.expect(id, request.whenBusy);\n return response;\n });\n },\n rewind: (messageId, context) => rewindIn(null, messageId, context),\n rewindAgent: (agentId, messageId, context) => rewindIn(agentId, messageId, context),\n\n async wait(id, context) {\n const parsed = submissionId(id);\n const submission =\n parsed === undefined ? undefined : await harness.submission(parsed, context);\n if (!submission) throw new Error(`unknown submission ${id}`);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) return { status: 'unanswered', text: null, reason: String(reason) };\n const entry = await harness.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return { status: 'done', text: answerText(entry?.model?.[0]?.content), reason: null };\n },\n withdraw: (id, context) => withdraw(current(), id, context),\n ...sprinkleControl(sprinkles),\n ...memoryControl(memory),\n ...freezerControl(freezer),\n async unqueue(agentId, id, context) {\n return withdraw(await conversationFor(agentId, context), id, context);\n },\n abort: (context) => current().abort(context),\n compact: (instructions, context) =>\n accepted(() => current().compact(instructions ?? undefined, context)),\n reset: (handoff, context) => current().reset(handoff ?? undefined, context),\n resolveLick(lickId, state, context) {\n return serial(async () => {\n if (!licks) return { done: false, text: null, error: 'this agent has no licks' };\n const conversation = current();\n const action = state === 'confirmed' ? 'confirm' : 'dismiss';\n try {\n const text = await licks.licks.decide(conversation, lickId, action, undefined, context);\n await conversation.submit(\n {\n type: 'write',\n entry: {\n kind: LICK_STATE_KIND,\n data: { lick: lickId, state, by: 'user' },\n model: [\n {\n role: 'user',\n content: `The user ${state} lick ${lickId}: ${text}`,\n timestamp: Date.now(),\n },\n ],\n },\n },\n context\n );\n return { done: true, text, error: null };\n } catch (error) {\n return { done: false, text: null, error: (error as Error).message };\n }\n });\n },\n async webhook(name, delivery, context) {\n const delivered = licks\n ? await licks.sources.webhook(\n name,\n {\n ...(delivery.id ? { id: delivery.id } : {}),\n headers: delivery.headers,\n body: delivery.body,\n },\n context\n )\n : false;\n return { delivered };\n },\n async stopAgent(agentId, context) {\n await (await conversationFor(agentId, context)).abort(context);\n },\n async selectCone(agentId, context) {\n await agents?.selectCone(agentId, context);\n },\n createCone(name, context) {\n return created(async () => {\n if (!agents) throw new Error('This agent has a single cone.');\n return agents.createCone(name, context);\n });\n },\n createScoop(parentId, name, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const roles = await scoops.runtime.roles(context);\n const answer = await scoops.scoops.spawn(\n { cone: parentId, name, prompts: [], fromAgent: false, limits: roles.limits },\n context\n );\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return `scoop:${answer.out.trim()}`;\n });\n },\n drop(agentId, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const answer = await scoops.scoops.stop(agentId, false, context);\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return agentId;\n });\n },\n configure: async (change, context) =>\n (await conversationFor(change.agentId, context)).configure(\n {\n ...(change.model ? { model: change.model } : {}),\n ...(change.thinkingLevel ? { thinkingLevel: change.thinkingLevel } : {}),\n },\n context\n ),\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EAEE;AAAA,EAEA;AAAA,OAMK;AACP,SAAS,kBAAkB;AAM3B,SAAS,uBAAuB;AAmBzB,SAAS,SAAS,KAAqB;AAC5C,QAAM,OAAO,IAAI,QAAQ,oBAAoB,EAAE,EAAE,KAAK;AACtD,QAAM,WAAW,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC;AAC5D,SAAO,SAAS,KAAK,QAAQ,IAAI,WAAW,GAAG,QAAQ;AACzD;AAEA,SAAS,QAAQ,KAA8C;AAC7D,SAAO,IAAI,EAAE;AAAA,IACX,CAAC,QAAQ,EAAE,IAAI,OAAO,KAAK;AAAA,IAC3B,CAAC,WAAkB,EAAE,IAAI,MAAM,OAAO,MAAM,QAAQ;AAAA,EACtD;AACF;AAEA,SAAS,eACP,SAC+D;AAC/D,QAAM,SAAS,MAAM;AACnB,QAAI,CAAC,QAAS,OAAM,IAAI,MAAM,4BAA4B;AAC1D,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,QAAQ,CAAC,SAAS,YAAY,QAAQ,YAAY,OAAO,EAAE,OAAO,SAAS,OAAO,CAAC;AAAA,IACnF,SAAS,CAAC,SAAS,YACjB,QAAQ,YAAa,MAAM,OAAO,EAAE,QAAQ,SAAS,OAAO,KAAM,EAAE;AAAA,IACtE,MAAM,CAAC,IAAI,YAAY,QAAQ,YAAY,OAAO,EAAE,KAAK,IAAI,OAAO,CAAC;AAAA,IACrE,SAAS,CAAC,IAAI,YACZ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W,OAAO,QAAQ,MAAM,OAAO;AAAA,UAC5E;AAAA,QACF;AACA,YAAI,OAAO,SAAS,EAAG,OAAM,IAAI,MAAM,SAAS,OAAO,GAAG,CAAC;AAC3D,eAAO,SAAS,OAAO,IAAI,KAAK,CAAC;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,IACA,KAAK,SAAS,SAAS;AACrB,aAAO,QAAQ,YAAY;AACzB,YAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,2BAA2B;AACxD,cAAM,SAAS,MAAM,OAAO,OAAO,KAAK,SAAS,OAAO,OAAO;AAC/D,YAAI,OAAO,SAAS,EAAG,OAAM,IAAI,MAAM,SAAS,OAAO,GAAG,CAAC;AAC3D,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,IACA,WAAW,OAAO,QAAQ,aACvB,MAAM,gBAAgB,OAAO,SAAS,OAAO,GAAG;AAAA,MAC/C;AAAA,QACE,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,QAC9C,GAAI,OAAO,gBAAgB,EAAE,eAAe,OAAO,cAAc,IAAI,CAAC;AAAA,MACxE;AAAA,MACA;AAAA,IACF;AAAA,EACJ;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { replicatedState } from "@earendil-works/chord";
|
|
2
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
3
|
+
import { answerText } from "../agent.js";
|
|
4
|
+
import { live } from "../agents.js";
|
|
5
|
+
import { SCOOPS_ROOT } from "../scoops/service.js";
|
|
6
|
+
const USAGE = `usage:
|
|
7
|
+
freezer list every frozen chat: id, name, title, messages, when
|
|
8
|
+
freezer show <id> a frozen chat as Markdown
|
|
9
|
+
freezer thaw <id> bring a frozen chat back as a cone
|
|
10
|
+
|
|
11
|
+
Freeze a cone, or start a new chat, from the chat toolbar or the command palette.
|
|
12
|
+
`;
|
|
13
|
+
const TITLE_LENGTH = 60;
|
|
14
|
+
function textOf(entry) {
|
|
15
|
+
return answerText(entry.model?.[0]?.content).trim();
|
|
16
|
+
}
|
|
17
|
+
function modelName(model) {
|
|
18
|
+
return model ? `${model.provider}/${model.modelId}` : "";
|
|
19
|
+
}
|
|
20
|
+
function firstLine(entries) {
|
|
21
|
+
const first = entries.find((entry) => entry.kind === "pi.user" && textOf(entry));
|
|
22
|
+
const line = first ? textOf(first).split("\n")[0].trim() : "";
|
|
23
|
+
if (!line) return "Untitled chat";
|
|
24
|
+
return line.length > TITLE_LENGTH ? `${line.slice(0, TITLE_LENGTH - 1)}\u2026` : line;
|
|
25
|
+
}
|
|
26
|
+
function calls(entry) {
|
|
27
|
+
const content = entry.model?.[0]?.content;
|
|
28
|
+
if (!Array.isArray(content)) return [];
|
|
29
|
+
return content.filter((part) => part.type === "toolCall").map((part) => `- \`${part.name}\` ${JSON.stringify(part.arguments ?? {})}`);
|
|
30
|
+
}
|
|
31
|
+
function markdown(record, entries) {
|
|
32
|
+
const out = [
|
|
33
|
+
`# ${record.title}`,
|
|
34
|
+
"",
|
|
35
|
+
`${record.name} \xB7 ${record.model} \xB7 frozen ${new Date(record.frozenAt).toISOString()}`
|
|
36
|
+
];
|
|
37
|
+
for (const entry of entries) {
|
|
38
|
+
if (entry.kind === "pi.user" && textOf(entry)) out.push("", "## User", "", textOf(entry));
|
|
39
|
+
if (entry.kind !== "pi.assistant") continue;
|
|
40
|
+
const text = textOf(entry);
|
|
41
|
+
const tools = calls(entry);
|
|
42
|
+
if (!text && !tools.length) continue;
|
|
43
|
+
out.push("", "## Assistant", "");
|
|
44
|
+
if (text) out.push(text);
|
|
45
|
+
if (tools.length) out.push(...text ? [""] : [], ...tools);
|
|
46
|
+
}
|
|
47
|
+
return `${out.join("\n")}
|
|
48
|
+
`;
|
|
49
|
+
}
|
|
50
|
+
function list(state) {
|
|
51
|
+
return Object.entries(state.frozen ?? {}).map(([id, record]) => ({
|
|
52
|
+
id,
|
|
53
|
+
name: record.name,
|
|
54
|
+
title: record.title,
|
|
55
|
+
model: record.model,
|
|
56
|
+
messages: record.messages,
|
|
57
|
+
frozenAt: record.frozenAt
|
|
58
|
+
})).sort((a, b) => b.frozenAt - a.frozenAt);
|
|
59
|
+
}
|
|
60
|
+
function freeName(state, wanted) {
|
|
61
|
+
const taken = new Set(Object.values(state.cones).map((cone) => cone.name));
|
|
62
|
+
if (!taken.has(wanted)) return wanted;
|
|
63
|
+
for (let n = 2; ; n++) if (!taken.has(`${wanted} ${n}`)) return `${wanted} ${n}`;
|
|
64
|
+
}
|
|
65
|
+
async function snapshot(conversation, name, now, context) {
|
|
66
|
+
const view = await conversation.context(context);
|
|
67
|
+
const agent = await conversation.agent(context);
|
|
68
|
+
return {
|
|
69
|
+
entries: view.entries,
|
|
70
|
+
record: {
|
|
71
|
+
name,
|
|
72
|
+
conversation: conversation.id,
|
|
73
|
+
title: firstLine(view.entries),
|
|
74
|
+
model: modelName(agent.model),
|
|
75
|
+
messages: view.entries.filter(
|
|
76
|
+
(entry) => entry.kind === "pi.user" || entry.kind === "pi.assistant"
|
|
77
|
+
).length,
|
|
78
|
+
frozenAt: now
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function frozenTarget(state, target) {
|
|
83
|
+
const records = Object.entries(state.frozen ?? {});
|
|
84
|
+
if (target.startsWith("cone:")) {
|
|
85
|
+
const cone = target.slice("cone:".length);
|
|
86
|
+
if (state.cones[cone]) return void 0;
|
|
87
|
+
const found = records.filter(([, record2]) => record2.cone === cone).sort(([, a], [, b]) => b.frozenAt - a.frozenAt)[0];
|
|
88
|
+
return found ? { id: found[0], name: found[1].name, at: found[1].frozenAt } : void 0;
|
|
89
|
+
}
|
|
90
|
+
const owner = state.scoops[target]?.frozen;
|
|
91
|
+
const record = owner ? state.frozen?.[owner] : void 0;
|
|
92
|
+
return owner && record ? { id: owner, name: record.name, at: record.frozenAt } : void 0;
|
|
93
|
+
}
|
|
94
|
+
async function command(options, runtime, argv, context) {
|
|
95
|
+
const verb = argv[0] ?? "help";
|
|
96
|
+
if (verb === "list") {
|
|
97
|
+
const rows = list(options.agents.state()).map(
|
|
98
|
+
(item) => `${item.id} ${item.name} ${item.title} ${item.messages} messages ${new Date(item.frozenAt).toISOString()}`
|
|
99
|
+
);
|
|
100
|
+
return { code: 0, out: rows.length ? `${rows.join("\n")}
|
|
101
|
+
` : "nothing is frozen\n" };
|
|
102
|
+
}
|
|
103
|
+
if (verb !== "show" && verb !== "thaw")
|
|
104
|
+
return { code: verb === "help" || verb === "--help" ? 0 : 2, out: USAGE };
|
|
105
|
+
const id = argv[1] ?? "";
|
|
106
|
+
const record = options.agents.state().frozen?.[id];
|
|
107
|
+
if (!record) return { code: 1, out: `freezer: there is no frozen chat ${id}
|
|
108
|
+
` };
|
|
109
|
+
if (verb === "thaw")
|
|
110
|
+
return { code: 0, out: `thawed ${id} as ${await runtime.thaw(id, context)}
|
|
111
|
+
` };
|
|
112
|
+
const conversation = await options.harness.conversation(record.conversation, context);
|
|
113
|
+
const entries = conversation ? (await conversation.context(context)).entries : [];
|
|
114
|
+
return { code: 0, out: markdown(record, entries) };
|
|
115
|
+
}
|
|
116
|
+
function attachFreezer(options) {
|
|
117
|
+
const { harness, agents, env } = options;
|
|
118
|
+
const now = options.now ?? Date.now;
|
|
119
|
+
const frozen = replicatedState(list(agents.state()));
|
|
120
|
+
const off = agents.onChange((state) => frozen.replace(BACKGROUND_CONTEXT, list(state)));
|
|
121
|
+
const conversationOf = async (agentId, context) => {
|
|
122
|
+
const conversation = await agents.conversation(agentId, context);
|
|
123
|
+
if (!conversation) throw new Error(`There is no cone ${agentId}.`);
|
|
124
|
+
return conversation;
|
|
125
|
+
};
|
|
126
|
+
const prepare = async (conversation, entries, cone, context) => {
|
|
127
|
+
const tail = entries.at(-1)?.id ?? 0;
|
|
128
|
+
await options.extract?.(conversation.id, tail, context, cone).catch(() => void 0);
|
|
129
|
+
};
|
|
130
|
+
const retitle = (id, model, entries, context) => {
|
|
131
|
+
if (!options.title) return;
|
|
132
|
+
const transcript = entries.filter((entry) => entry.kind === "pi.user" || entry.kind === "pi.assistant").map((entry) => `${entry.kind === "pi.user" ? "User" : "Agent"}: ${textOf(entry)}`).join("\n").slice(0, 4e3);
|
|
133
|
+
void options.title(transcript, model, context).then(async (title) => {
|
|
134
|
+
const clean = title?.replace(/\s+/g, " ").replace(/^["'“”]+|["'“”]+$/g, "").replace(/\.+$/, "").trim();
|
|
135
|
+
if (!clean) return;
|
|
136
|
+
await agents.update((_tx, doc) => {
|
|
137
|
+
const record = doc.frozen?.[id];
|
|
138
|
+
if (record) record.title = clean.slice(0, TITLE_LENGTH);
|
|
139
|
+
}, context);
|
|
140
|
+
}).catch(() => void 0);
|
|
141
|
+
};
|
|
142
|
+
const replacement = async (coneId, context) => {
|
|
143
|
+
const state = agents.state();
|
|
144
|
+
const other = Object.keys(state.cones).find((id) => id !== coneId);
|
|
145
|
+
if (other) return { id: other, conversation: void 0 };
|
|
146
|
+
const current = await conversationOf(coneId, context);
|
|
147
|
+
const conversation = await harness.createConversation(
|
|
148
|
+
{
|
|
149
|
+
ownership: { kind: "ownerless" },
|
|
150
|
+
agent: { model: (await current.agent(context)).model }
|
|
151
|
+
},
|
|
152
|
+
context
|
|
153
|
+
);
|
|
154
|
+
return { id: `cone-${state.next}`, conversation };
|
|
155
|
+
};
|
|
156
|
+
const runtime = {
|
|
157
|
+
frozen,
|
|
158
|
+
async freeze(agentId, context) {
|
|
159
|
+
const cone = agents.state().cones[agentId];
|
|
160
|
+
if (!cone) throw new Error(`There is no cone ${agentId}.`);
|
|
161
|
+
const conversation = await conversationOf(agentId, context);
|
|
162
|
+
const { entries, record } = await snapshot(conversation, cone.name, now(), context);
|
|
163
|
+
await prepare(conversation, entries, agentId, context);
|
|
164
|
+
await conversation.abort(context, { background: true }).catch(() => void 0);
|
|
165
|
+
const next = agents.state().active === agentId ? await replacement(agentId, context) : void 0;
|
|
166
|
+
const { id, scoops } = await agents.update((_tx, doc) => {
|
|
167
|
+
if (!doc.cones[agentId]) throw new Error(`There is no cone ${agentId}.`);
|
|
168
|
+
const frozenId = `frozen-${doc.frozenNext ?? 1}`;
|
|
169
|
+
const owned = Object.entries(doc.scoops).filter(([, scoop]) => scoop.cone === agentId && live(scoop)).map(([scoop]) => scoop);
|
|
170
|
+
doc.frozenNext = (doc.frozenNext ?? 1) + 1;
|
|
171
|
+
doc.frozen ??= {};
|
|
172
|
+
doc.frozen[frozenId] = { ...record, cone: agentId, scoops: owned };
|
|
173
|
+
delete doc.cones[agentId];
|
|
174
|
+
for (const scoop of owned) doc.scoops[scoop].frozen = frozenId;
|
|
175
|
+
if (next?.conversation) {
|
|
176
|
+
doc.cones[next.id] = { name: record.name, conversation: next.conversation.id };
|
|
177
|
+
doc.next += 1;
|
|
178
|
+
}
|
|
179
|
+
return { id: frozenId, scoops: owned };
|
|
180
|
+
}, context);
|
|
181
|
+
for (const scoop of scoops)
|
|
182
|
+
await (await agents.conversation(scoop, context))?.abort(context).catch(() => void 0);
|
|
183
|
+
if (next) await agents.selectCone(next.id, context);
|
|
184
|
+
retitle(id, record.model, entries, context);
|
|
185
|
+
return id;
|
|
186
|
+
},
|
|
187
|
+
async newChat(agentId, context) {
|
|
188
|
+
const cone = agents.state().cones[agentId];
|
|
189
|
+
if (!cone) throw new Error(`There is no cone ${agentId}.`);
|
|
190
|
+
const conversation = await conversationOf(agentId, context);
|
|
191
|
+
const before = (await conversation.context(context)).entries;
|
|
192
|
+
if (!before.some((entry) => entry.kind === "pi.user")) return null;
|
|
193
|
+
const agent = await conversation.agent(context);
|
|
194
|
+
const fresh = await harness.createConversation(
|
|
195
|
+
{
|
|
196
|
+
ownership: { kind: "ownerless" },
|
|
197
|
+
agent: {
|
|
198
|
+
model: agent.model,
|
|
199
|
+
thinkingLevel: agent.thinkingLevel,
|
|
200
|
+
extensions: agent.extensions,
|
|
201
|
+
tools: agent.tools,
|
|
202
|
+
instructions: agent.instructions ?? null,
|
|
203
|
+
cwd: agent.cwd ?? null
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
context
|
|
207
|
+
);
|
|
208
|
+
await agents.setConversation(agentId, fresh, context);
|
|
209
|
+
await conversation.abort(context).catch(() => void 0);
|
|
210
|
+
const { entries, record } = await snapshot(conversation, cone.name, now(), context);
|
|
211
|
+
await prepare(conversation, entries, agentId, context);
|
|
212
|
+
const id = await agents.update((_tx, doc) => {
|
|
213
|
+
const frozenId = `frozen-${doc.frozenNext ?? 1}`;
|
|
214
|
+
doc.frozenNext = (doc.frozenNext ?? 1) + 1;
|
|
215
|
+
doc.frozen ??= {};
|
|
216
|
+
doc.frozen[frozenId] = { ...record, cone: agentId, scoops: [] };
|
|
217
|
+
return frozenId;
|
|
218
|
+
}, context);
|
|
219
|
+
retitle(id, record.model, entries, context);
|
|
220
|
+
return id;
|
|
221
|
+
},
|
|
222
|
+
async thaw(id, context) {
|
|
223
|
+
const coneId = await agents.update((_tx, doc) => {
|
|
224
|
+
const record = doc.frozen?.[id];
|
|
225
|
+
if (!record) throw new Error(`There is no frozen chat ${id}.`);
|
|
226
|
+
const reuse = !doc.cones[record.cone];
|
|
227
|
+
const target = reuse ? record.cone : `cone-${doc.next}`;
|
|
228
|
+
if (!reuse) doc.next += 1;
|
|
229
|
+
doc.cones[target] = { name: freeName(doc, record.name), conversation: record.conversation };
|
|
230
|
+
for (const scoop of record.scoops) {
|
|
231
|
+
const entry = doc.scoops[scoop];
|
|
232
|
+
if (!entry) continue;
|
|
233
|
+
delete entry.frozen;
|
|
234
|
+
entry.cone = target;
|
|
235
|
+
}
|
|
236
|
+
delete doc.frozen?.[id];
|
|
237
|
+
return target;
|
|
238
|
+
}, context);
|
|
239
|
+
await agents.selectCone(coneId, context);
|
|
240
|
+
return coneId;
|
|
241
|
+
},
|
|
242
|
+
async discard(id, context) {
|
|
243
|
+
const record = agents.state().frozen?.[id];
|
|
244
|
+
if (!record) throw new Error(`There is no frozen chat ${id}.`);
|
|
245
|
+
const folders = record.scoops.map((scoop) => agents.state().scoops[scoop]?.folder).filter((folder) => Boolean(folder));
|
|
246
|
+
await agents.update((_tx, doc) => {
|
|
247
|
+
for (const scoop of record.scoops) {
|
|
248
|
+
const entry = doc.scoops[scoop];
|
|
249
|
+
if (!entry) continue;
|
|
250
|
+
delete entry.frozen;
|
|
251
|
+
entry.gone = true;
|
|
252
|
+
}
|
|
253
|
+
delete doc.frozen?.[id];
|
|
254
|
+
}, context);
|
|
255
|
+
for (const folder of folders)
|
|
256
|
+
await env.remove(`${SCOOPS_ROOT}/${folder}`, { recursive: true, force: true }, context);
|
|
257
|
+
},
|
|
258
|
+
frozenTarget: (target) => frozenTarget(agents.state(), target),
|
|
259
|
+
command: (argv, _caller, context) => command(options, runtime, argv, context),
|
|
260
|
+
close: () => off()
|
|
261
|
+
};
|
|
262
|
+
return runtime;
|
|
263
|
+
}
|
|
264
|
+
export {
|
|
265
|
+
USAGE,
|
|
266
|
+
attachFreezer,
|
|
267
|
+
firstLine,
|
|
268
|
+
frozenTarget,
|
|
269
|
+
markdown,
|
|
270
|
+
modelName
|
|
271
|
+
};
|
|
272
|
+
//# sourceMappingURL=index.js.map
|