@iiiokojiadbi/shift 0.29.0 → 0.31.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 CHANGED
@@ -1,12 +1,15 @@
1
- # shift for pi
1
+ # shift for pi and opencode
2
2
 
3
- The agent decides by itself when to **shift**. At a stage boundary it updates its work board and task folders, writes a letter to itself, and has pi let the stretch's history go, with a direction of what to hold. Right after the shift it gets its letter, board and tasks in progress back whole and continues from where it stopped.
3
+ The agent decides by itself when to **shift**. At a stage boundary it updates its work board and task folders, writes a letter to itself, and has the harness let the stretch's history go, with a direction of what to hold. Right after the shift it gets its letter, board and tasks in progress back whole and continues from where it stopped.
4
+
5
+ One package for both harnesses: pi loads `index.ts`, opencode loads `server.ts`.
4
6
 
5
7
  ```sh
6
8
  pi install npm:@iiiokojiadbi/shift
9
+ opencode plugin add @iiiokojiadbi/shift
7
10
  ```
8
11
 
9
- The extension adds a "Shift" section to the system prompt, the `shift` tool with its companions (`shift_guide`, `shift_status`, `shift_history`, `shift_setup`, `task_open`, `task_track`, `task_archive`, `doc_outline`, `docs_mentioning`), and two commands: `/shift-tasks` lists the open tasks, `/unshift` picks up the last shift in a fresh session. It hints a shift as the history grows.
12
+ It adds a "Shift" section to the system prompt, the `shift` tool with its companions (`shift_guide`, `shift_status`, `shift_history`, `shift_setup`, `task_open`, `task_track`, `task_archive`, `doc_outline`, `docs_mentioning`), and three commands: `/shift` asks the agent to shift now, `/shift-tasks` lists the open tasks, `/unshift` picks up the last shift in a fresh session. It hints a shift as the history grows.
10
13
 
11
14
  The records live in the project's `.shift/` folder and stay out of its git unless `commit = true` in `.shift/settings.toml`.
12
15
 
package/core/layout.ts CHANGED
@@ -26,6 +26,8 @@ export const RESUME_COMMAND = 'unshift'
26
26
 
27
27
  export const TASKS_COMMAND = 'shift-tasks'
28
28
 
29
+ export const SHIFT_COMMAND = 'shift'
30
+
29
31
  // The board is the state of the work; past this it has turned into a diary.
30
32
  export const BOARD_MAX_LINES = 150
31
33
 
@@ -18,8 +18,10 @@ import {
18
18
  OWNER,
19
19
  RESUME_COMMAND,
20
20
  SETTINGS,
21
+ SHIFT_COMMAND,
21
22
  TASK_LIST,
22
23
  TASKS,
24
+ TOOL,
23
25
  TRACK_TOOL,
24
26
  } from '../layout'
25
27
  import { frontmatter } from '../markdown'
@@ -179,7 +181,7 @@ function shiftMessage(opening: string, letter: string, back: HandedBack, closing
179
181
  `<${MOD} folder="${dir}/">`,
180
182
  opening,
181
183
  '',
182
- 'The board, the tasks in progress and the map of knowledge, as they are now; SHIFT.md, OWNER.md, GLOSSARY.md and TASKS.md are in your session block, read again after this shift:',
184
+ 'The board, the tasks in progress and the map of knowledge, as they are now; the files of your session block were read again after this shift:',
183
185
  '',
184
186
  renderWork(work, back.knowledge, back.owner),
185
187
  '',
@@ -207,7 +209,7 @@ export function continuePrompt(letter: string, back: HandedBack): string {
207
209
  }
208
210
 
209
211
  export function waitContext(letter: string, back: HandedBack): string {
210
- return shiftMessage("You shifted and waited for the owner; the owner's message is above.", letter, back, [GUIDE_KNOWN])
212
+ return shiftMessage("You shifted and waited for the owner; the owner's message comes with this one.", letter, back, [GUIDE_KNOWN])
211
213
  }
212
214
 
213
215
  export function resumePrompt(letter: string, back: HandedBack): string {
@@ -225,6 +227,10 @@ export function resumePrompt(letter: string, back: HandedBack): string {
225
227
  // What starts the turn after /unshift when the owner wrote nothing with it: the letter is already in the history.
226
228
  export const RESUME_GO = `<${MOD} note="from the mod after /${RESUME_COMMAND}">Pick up from the shift above: continue from "${NEXT}".</${MOD}>`
227
229
 
230
+ // The owner's /shift: their word to shift now, the first hint or not, with what they typed after the command.
231
+ export const SHIFT_NOW = (words: string) =>
232
+ `<${MOD} note="from the owner's /${SHIFT_COMMAND}">The owner asks you to shift now, whether a hint has come or not. Bring the step in hand to a point the letter can name, keep your records, write the letter and call ${TOOL}; choose after as the work needs.${words === '' ? '' : ` The owner's words: ${words}`}</${MOD}>`
233
+
228
234
  // How the turn ends once a shift is accepted. The owner reads the turn's last message, not the letter or the records:
229
235
  // with `wait` it is the answer they come back to.
230
236
  const TURN_END: Record<ShiftAfter, string> = {
@@ -36,6 +36,8 @@ export const SETUP_DESCRIPTION =
36
36
 
37
37
  export const TASKS_DESCRIPTION = 'The open tasks and the items of those in progress, read from .shift/; the agent is not asked'
38
38
 
39
+ export const SHIFT_NOW_DESCRIPTION = 'Ask the agent to shift now; words typed after it go to the agent with the ask'
40
+
39
41
  export const RESUME_DESCRIPTION = 'Pick up the work from the last shift: the letter, the board and the tasks in progress go to the agent'
40
42
 
41
43
  export const SETUP_SCHEMA = { type: 'object', properties: {} }
package/index.ts CHANGED
@@ -23,6 +23,9 @@ import {
23
23
  RESUME_DESCRIPTION,
24
24
  resumeShift,
25
25
  SETTINGS,
26
+ SHIFT_COMMAND,
27
+ SHIFT_NOW,
28
+ SHIFT_NOW_DESCRIPTION,
26
29
  SOURCES,
27
30
  sessionDoctrine,
28
31
  sessionFiles,
@@ -90,6 +93,15 @@ export default function shift(pi: ExtensionAPI): void {
90
93
  handler: async (_args, ctx) => ctx.ui.notify(await tasksView(await projectAt(ctx.cwd)), 'info'),
91
94
  })
92
95
 
96
+ pi.registerCommand(SHIFT_COMMAND, {
97
+ description: SHIFT_NOW_DESCRIPTION,
98
+ handler: async (args, ctx) => {
99
+ if (!enabled) return ctx.ui.notify(`${MOD} is off in this project: ${SETTINGS} has enabled = false.`, 'info')
100
+ // Typed mid-run, it waits for the run to end, as Claude Code holds a command until the turn is over.
101
+ pi.sendUserMessage(SHIFT_NOW(args.trim()), ctx.isIdle() ? undefined : { deliverAs: 'followUp' })
102
+ },
103
+ })
104
+
93
105
  pi.registerCommand(RESUME_COMMAND, {
94
106
  description: RESUME_DESCRIPTION,
95
107
  // The owner's words typed with the command go after the letter, as their own message that starts the turn.
package/package.json CHANGED
@@ -1,24 +1,30 @@
1
1
  {
2
2
  "name": "@iiiokojiadbi/shift",
3
- "version": "0.29.0",
3
+ "version": "0.31.0",
4
4
  "description": "The agent decides by itself when to shift: it keeps a work board and task folders, writes a letter to itself, and continues from where it stopped.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/iiiokojiadbi/shift.git",
10
- "directory": "adapters/pi"
10
+ "directory": "adapters/npm"
11
11
  },
12
12
  "keywords": [
13
- "pi-package"
13
+ "pi-package",
14
+ "opencode-plugin"
14
15
  ],
15
16
  "files": [
16
17
  "index.ts",
18
+ "server.ts",
17
19
  "store.ts",
18
20
  "core",
19
21
  "README.md",
20
22
  "LICENSE"
21
23
  ],
24
+ "exports": {
25
+ "./server": "./server.ts",
26
+ "./package.json": "./package.json"
27
+ },
22
28
  "pi": {
23
29
  "extensions": [
24
30
  "./index.ts"
@@ -27,5 +33,13 @@
27
33
  "peerDependencies": {
28
34
  "@earendil-works/pi-coding-agent": "*",
29
35
  "typebox": "*"
36
+ },
37
+ "peerDependenciesMeta": {
38
+ "@earendil-works/pi-coding-agent": {
39
+ "optional": true
40
+ },
41
+ "typebox": {
42
+ "optional": true
43
+ }
30
44
  }
31
45
  }
package/server.ts ADDED
@@ -0,0 +1,418 @@
1
+ import { resolve } from 'node:path'
2
+ import type { Plugin } from '@opencode/plugin'
3
+ import type { Courier, Gauge, GaugeKeeper, LetGoHarness, Level, Looks, Loop, LoopState, Note, WaitNote } from './core/index'
4
+ import {
5
+ addGrowth,
6
+ afterTool,
7
+ afterTurn,
8
+ afterWrite,
9
+ atPrompt,
10
+ beforeTool,
11
+ contentChars,
12
+ countGrowth,
13
+ FRESH_GAUGE,
14
+ FRESH_LOOKS,
15
+ FRESH_LOOP,
16
+ gaugeStatus,
17
+ letGoGauge,
18
+ MOD,
19
+ RESUME_COMMAND,
20
+ RESUME_DESCRIPTION,
21
+ renderSessionFiles,
22
+ resumeShift,
23
+ SHIFT_COMMAND,
24
+ SHIFT_NOW,
25
+ SHIFT_NOW_DESCRIPTION,
26
+ SOURCES,
27
+ sessionDoctrine,
28
+ sessionFiles,
29
+ shiftBase,
30
+ startSession,
31
+ TASKS_COMMAND,
32
+ TASKS_DESCRIPTION,
33
+ TOOLS,
34
+ tasksView,
35
+ unassistedInstructions,
36
+ } from './core/index'
37
+ import { projectAt } from './store'
38
+
39
+ type Definition = Plugin.Plugin
40
+
41
+ const OURS: ReadonlySet<string> = new Set(TOOLS.map(tool => tool.name))
42
+ // opencode's tools that only read, and those that write one file by `path`.
43
+ const READING: ReadonlySet<string> = new Set(['read', 'glob', 'grep'])
44
+ const WRITING: ReadonlySet<string> = new Set(['edit', 'write'])
45
+ // opencode keeps this much of the latest history whole beside the digest, unless its config says otherwise.
46
+ const KEPT_TOKENS = 15_000
47
+ // A token is about four characters: the step's tokens stand for the response's text, which the event does not carry.
48
+ const CHARS_PER_TOKEN = 4
49
+ // The rows the owner sees above what the mod sends the agent.
50
+ const CONTINUED = `${MOD}: the letter and the records`
51
+ const NOTES = `${MOD}: notes to the agent`
52
+
53
+ // What the plugin keeps of one session; the plugin is one per project, shared by its sessions.
54
+ type Session = {
55
+ loop: LoopState
56
+ gauge: Gauge
57
+ looks: Looks
58
+ // The last step's prompt size: the history as the model read it.
59
+ fill: number | undefined
60
+ // A run is going on; set when it starts, cleared at idle.
61
+ busy: boolean
62
+ // The Hold of the shift being let go, and what its let-go ended in.
63
+ hold: string | undefined
64
+ letGo: ((end: { text: string } | { error: string }) => void) | undefined
65
+ // The doctrine and the session's files as the session started or last let go: a block read anew every
66
+ // request would show records the history has not reached yet and break the prompt's cache on every write.
67
+ block: string[] | undefined
68
+ }
69
+
70
+ type Ended = { sessionID: string; text?: string; error?: unknown; tokens?: { input?: number } }
71
+
72
+ const plugin: Definition = {
73
+ id: MOD,
74
+ async setup(ctx) {
75
+ const root = ctx.location.directory
76
+ const start = await startSession(await projectAt(root))
77
+ if (!start.enabled) return
78
+
79
+ const sessions = new Map<string, Session>()
80
+ const children = new Map<string, boolean>()
81
+ const windows = new Map<string, { window: number; threshold: number | undefined }>()
82
+ const outside = new Map<string, Note[]>()
83
+ let stopped = false
84
+
85
+ // A session's state, its waiting letter read back from the plugin's storage the first time: it outlives a restart.
86
+ async function state(sessionID: string): Promise<Session> {
87
+ const known = sessions.get(sessionID)
88
+ if (known !== undefined) return known
89
+ const note = ((await ctx.storage.get(waitKey(sessionID))) ?? null) as WaitNote | null
90
+ const fresh: Session = {
91
+ loop: { ...FRESH_LOOP, note },
92
+ gauge: FRESH_GAUGE,
93
+ looks: FRESH_LOOKS,
94
+ fill: undefined,
95
+ busy: false,
96
+ hold: undefined,
97
+ letGo: undefined,
98
+ block: undefined,
99
+ }
100
+ sessions.set(sessionID, sessions.get(sessionID) ?? fresh)
101
+
102
+ return sessions.get(sessionID) ?? fresh
103
+ }
104
+
105
+ // A subagent runs in a child session: only the main agent shifts and is told.
106
+ async function child(sessionID: string): Promise<boolean> {
107
+ const known = children.get(sessionID)
108
+ if (known !== undefined) return known
109
+ const info = await ctx.session.get({ sessionID }).catch(() => undefined)
110
+ const parent = info?.parentID !== undefined
111
+ children.set(sessionID, parent)
112
+
113
+ return parent
114
+ }
115
+
116
+ // A row for the owner: a synthetic message the owner sees by its description; the agent reads it with the next one.
117
+ async function tell(sessionID: string, row: string, _level: Level): Promise<void> {
118
+ await ctx.session.synthetic({ sessionID, text: row, description: row, resume: false }).catch(() => {})
119
+ }
120
+
121
+ function loopOf(sessionID: string): Loop {
122
+ return {
123
+ read: async () => (await state(sessionID)).loop,
124
+ update: async change => {
125
+ const session = await state(sessionID)
126
+ const before = session.loop.note
127
+ session.loop = change(session.loop)
128
+ const { note } = session.loop
129
+ if (note === before) return
130
+ if (note === null) await ctx.storage.remove(waitKey(sessionID))
131
+ else await ctx.storage.set(waitKey(sessionID), note)
132
+ },
133
+ tell: (row, level) => void tell(sessionID, row, level),
134
+ }
135
+ }
136
+
137
+ function courierOf(sessionID: string): Courier {
138
+ return {
139
+ loop: loopOf(sessionID),
140
+ gauge: keeperOf(sessionID),
141
+ project: () => projectAt(root),
142
+ looks: async () => (await state(sessionID)).looks,
143
+ updateLooks: async change => {
144
+ const session = await state(sessionID)
145
+ session.looks = change(session.looks)
146
+ },
147
+ }
148
+ }
149
+
150
+ // The gauge in the plugin's memory; the history and the base read from the session.
151
+ function keeperOf(sessionID: string): GaugeKeeper {
152
+ return {
153
+ read: async () => (await state(sessionID)).gauge,
154
+ update: async change => {
155
+ const session = await state(sessionID)
156
+ session.gauge = change(session.gauge)
157
+ },
158
+ history: async () => growthIn(await ctx.session.context({ sessionID })),
159
+ base: async () => shiftBase(await projectAt(root), sessionID),
160
+ reading: async () => ({ tokens: (await state(sessionID)).fill, ...(await limits(sessionID)) }),
161
+ }
162
+ }
163
+
164
+ // The model's window and where opencode lets the history go by itself: the window less max(15%, 16K), its default.
165
+ async function limits(sessionID: string): Promise<{ window: number; threshold: number | undefined }> {
166
+ const known = windows.get(sessionID)
167
+ if (known !== undefined) return known
168
+ const info = await ctx.session.get({ sessionID }).catch(() => undefined)
169
+ const models = info?.model === undefined ? [] : ((await ctx.model.list().catch(() => undefined))?.data ?? [])
170
+ const model = models.find(each => each.id === info?.model?.id && each.providerID === info?.model?.providerID)
171
+ const window = model?.limit.input || model?.limit.context || 0
172
+ if (window === 0) return { window: 0, threshold: undefined }
173
+ const buffer =
174
+ typeof ctx.options.buffer === 'number' ? ctx.options.buffer : Math.max(Math.floor(window * 0.15), window >= 32_000 ? 16_000 : 0)
175
+ const found = { window, threshold: window - buffer }
176
+ windows.set(sessionID, found)
177
+
178
+ return found
179
+ }
180
+
181
+ // opencode lets go through a compaction the runner takes once the session is idle; the Hold rides on its hook.
182
+ function letGoOf(sessionID: string): LetGoHarness {
183
+ return {
184
+ fill: async () => (await state(sessionID)).fill,
185
+ letGo: async instructions => {
186
+ const session = await state(sessionID)
187
+ const before = session.fill
188
+ const ended = new Promise<{ text: string } | { error: string }>(done => {
189
+ session.letGo = done
190
+ })
191
+ session.hold = instructions
192
+ try {
193
+ await ctx.session.compact({ sessionID, delivery: 'queue' })
194
+ const end = await ended
195
+ if ('error' in end) return { skip: end.error }
196
+ await ctx.session.wait({ sessionID })
197
+ // The next step measures it; until then the digest and the kept tail stand for it.
198
+ const after = Math.round(end.text.length / CHARS_PER_TOKEN) + Math.min(before ?? 0, KEPT_TOKENS)
199
+
200
+ return { messages: [{ role: 'digest', text: end.text }], before, after }
201
+ } finally {
202
+ session.hold = undefined
203
+ session.letGo = undefined
204
+ }
205
+ },
206
+ continueWith: async prompt => {
207
+ await ctx.session.synthetic({ sessionID, text: prompt, description: CONTINUED })
208
+ },
209
+ }
210
+ }
211
+
212
+ // The doctrine and the session's files, read at the session's first request and again after each let-go.
213
+ await ctx.session.hook('context', async event => {
214
+ if (await child(event.sessionID)) return
215
+ const session = await state(event.sessionID)
216
+ if (session.block === undefined) {
217
+ const project = await projectAt(root)
218
+ const files = renderSessionFiles(await sessionFiles(project))
219
+ session.block = [sessionDoctrine(project.settings).doctrine, ...(files === null ? [] : [files])]
220
+ }
221
+ for (const text of session.block) event.system.push({ type: 'text', text })
222
+ })
223
+
224
+ // A compaction the agent asked for holds what its letter says; any other gets the summarizer's instructions.
225
+ await ctx.session.hook('compaction', async event => {
226
+ const hold = sessions.get(event.sessionID)?.hold
227
+ const text = hold ?? unassistedInstructions((await projectAt(root)).settings.files)
228
+ event.system.push({ type: 'text', text })
229
+ })
230
+
231
+ // The owner's message: what changed between turns, a hint, and after a wait the letter go with it.
232
+ await ctx.session.hook('prompt', async event => {
233
+ if (await child(event.sessionID)) return
234
+ const { sessionID } = event
235
+ await countGrowth(keeperOf(sessionID), SOURCES.owner, event.prompt.text.length)
236
+ const told = await atPrompt(courierOf(sessionID), { runStarts: !(await state(sessionID)).busy, owner: true })
237
+ if (told.notes.length === 0) return
238
+ const text = told.notes.join('\n\n')
239
+ await ctx.session.synthetic({ sessionID, text, description: NOTES, resume: false })
240
+ await countGrowth(keeperOf(sessionID), SOURCES.attachments, text.length)
241
+ await told.delivered()
242
+ })
243
+
244
+ // Every note to the agent mid-run goes with a tool's result: what changed in the records around a tool of the agent,
245
+ // the docs after a write, a hint. A subagent's write gets only the docs.
246
+ await ctx.tool.hook('execute.before', async event => {
247
+ if (await child(event.sessionID)) return
248
+ outside.set(event.id, await beforeTool(courierOf(event.sessionID)))
249
+ })
250
+
251
+ await ctx.tool.hook('execute.after', async event => {
252
+ const { sessionID } = event
253
+ const done = event.status === 'completed' ? event.result : null
254
+ const path = done !== null && WRITING.has(event.tool) ? (event.input as { path?: unknown }).path : undefined
255
+ const written = typeof path === 'string' ? resolve(root, path) : undefined
256
+ if (done !== null) await countGrowth(keeperOf(sessionID), event.tool, contentChars(done.content))
257
+ let added: string[]
258
+ if (!(await child(sessionID))) {
259
+ const before = outside.get(event.id) ?? []
260
+ outside.delete(event.id)
261
+ const end = done === null ? null : { own: OURS.has(event.tool), readOnly: READING.has(event.tool), written }
262
+ added = await afterTool(courierOf(sessionID), before, end)
263
+ } else added = written === undefined ? [] : await afterWrite(courierOf(sessionID), written)
264
+ if (done === null || added.length === 0) return
265
+ const blocks = added.map(text => ({ type: 'text' as const, text }))
266
+ const content = typeof done.content === 'string' ? [{ type: 'text' as const, text: done.content }] : (done.content ?? [])
267
+ if (event.status === 'completed') event.result = { ...done, content: [...content, ...blocks] }
268
+ })
269
+
270
+ await ctx.tool.transform(tools => {
271
+ for (const tool of start.tools) {
272
+ tools.add({
273
+ name: tool.name,
274
+ description: tool.description,
275
+ input: tool.schema,
276
+ // Called by its name, not through the code-mode tool.
277
+ options: { codemode: false },
278
+ execute: async (input, call) => {
279
+ const done = await tool.run(input as Record<string, unknown>, {
280
+ project: () => projectAt(root),
281
+ sessionId: async () => call.sessionID,
282
+ now: async () => Date.now(),
283
+ subagent: await child(call.sessionID),
284
+ loop: loopOf(call.sessionID),
285
+ // The session's files are read anew before every request, so this copy is never older than them.
286
+ loaded: async () => null,
287
+ status: () => gaugeStatus(keeperOf(call.sessionID)),
288
+ cannotLetGo: async () => null,
289
+ })
290
+ if ('deny' in done) throw new Error(done.deny)
291
+
292
+ return { content: done.result }
293
+ },
294
+ })
295
+ }
296
+ })
297
+
298
+ await ctx.command.transform(commands => {
299
+ // The owner's word to shift: once the run going on is over, a turn of its own.
300
+ commands.add({
301
+ name: SHIFT_COMMAND,
302
+ description: SHIFT_NOW_DESCRIPTION,
303
+ execute: async ({ sessionID, prompt }) => {
304
+ await ctx.session.synthetic({
305
+ sessionID,
306
+ text: SHIFT_NOW(prompt.text.trim()),
307
+ description: `/${SHIFT_COMMAND}`,
308
+ delivery: 'queue',
309
+ })
310
+ },
311
+ })
312
+ // The letter first; the owner's words typed with the command come after it as their own message.
313
+ commands.add({
314
+ name: RESUME_COMMAND,
315
+ description: RESUME_DESCRIPTION,
316
+ execute: async ({ sessionID, prompt }) => {
317
+ const resumed = await resumeShift(await projectAt(root))
318
+ const words = prompt.text.trim()
319
+ if (resumed.prompt === undefined) return tell(sessionID, resumed.text, 'info')
320
+ await ctx.session.synthetic({ sessionID, text: resumed.prompt, description: resumed.text, resume: words === '' })
321
+ if (words !== '') await ctx.session.prompt({ sessionID, text: words })
322
+ },
323
+ })
324
+ // For the owner: it asks the agent nothing; the agent reads it with the next message.
325
+ commands.add({
326
+ name: TASKS_COMMAND,
327
+ description: TASKS_DESCRIPTION,
328
+ execute: async ({ sessionID }) => tell(sessionID, await tasksView(await projectAt(root)), 'info'),
329
+ })
330
+ })
331
+
332
+ // The runs and the let-gos, by the server's events; a let-go is awaited outside the loop that reads its end.
333
+ async function onEvent(event: { type: string; data?: unknown }): Promise<void> {
334
+ const data = (event.data ?? {}) as Ended & { tokens?: Tokens; reason?: string }
335
+ if (typeof data.sessionID !== 'string' || (await child(data.sessionID))) return
336
+ const session = await state(data.sessionID)
337
+ switch (event.type) {
338
+ case 'session.execution.started':
339
+ session.busy = true
340
+ return
341
+ case 'session.step.ended': {
342
+ const tokens = data.tokens as Tokens | undefined
343
+ if (tokens === undefined) return
344
+ session.fill = (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0)
345
+ const said = ((tokens.output ?? 0) + (tokens.reasoning ?? 0)) * CHARS_PER_TOKEN
346
+ await countGrowth(keeperOf(data.sessionID), SOURCES.responses, said)
347
+ return
348
+ }
349
+ case 'session.compaction.ended':
350
+ session.gauge = letGoGauge(data.reason === 'auto')
351
+ session.fill = undefined
352
+ session.block = undefined
353
+ session.letGo?.({ text: data.text ?? '' })
354
+ return
355
+ case 'session.compaction.failed':
356
+ session.letGo?.({ error: `the compaction failed: ${errorText(data.error)}` })
357
+ return
358
+ // A run is over, whichever way it ended: a shift held in it lets go now, unless the owner interrupted it.
359
+ case 'session.execution.succeeded':
360
+ case 'session.execution.failed':
361
+ case 'session.execution.interrupted': {
362
+ session.busy = false
363
+ const courier = courierOf(data.sessionID)
364
+ await courier.updateLooks(current => (current.running === 0 ? current : { ...current, running: 0 }))
365
+ if (session.loop.pending === null) return
366
+ const aborted = event.type === 'session.execution.interrupted'
367
+ void afterTurn(await projectAt(root), loopOf(data.sessionID), letGoOf(data.sessionID), aborted)
368
+ return
369
+ }
370
+ }
371
+ }
372
+
373
+ void (async () => {
374
+ for await (const event of ctx.event.subscribe()) {
375
+ if (stopped) return
376
+ await onEvent(event as { type: string; data?: unknown }).catch(() => {})
377
+ }
378
+ })()
379
+
380
+ return () => {
381
+ stopped = true
382
+ }
383
+ },
384
+ }
385
+
386
+ export default plugin
387
+
388
+ type Tokens = { input?: number; output?: number; reasoning?: number; cache?: { read?: number; write?: number } }
389
+
390
+ // The waiting letter of a session, in the plugin's storage.
391
+ function waitKey(sessionID: string): string {
392
+ return `wait:${sessionID}`
393
+ }
394
+
395
+ function errorText(error: unknown): string {
396
+ if (typeof error === 'string') return error
397
+ if (typeof error === 'object' && error !== null && 'message' in error) return String(error.message)
398
+
399
+ return JSON.stringify(error)
400
+ }
401
+
402
+ // The growth of the history since the last let-go, counted the way rows are counted as they come.
403
+ function growthIn(messages: readonly unknown[]): Record<string, number> {
404
+ let gauge = FRESH_GAUGE
405
+ for (const message of messages as { type: string; text?: string; content?: unknown }[]) {
406
+ if (message.type === 'compaction') gauge = FRESH_GAUGE
407
+ else if (message.type === 'user') gauge = addGrowth(gauge, SOURCES.owner, message.text?.length ?? 0)
408
+ else if (message.type === 'synthetic') gauge = addGrowth(gauge, SOURCES.attachments, message.text?.length ?? 0)
409
+ else if (message.type === 'assistant' && Array.isArray(message.content)) {
410
+ for (const block of message.content as { type: string; name?: string; state?: { content?: unknown } }[]) {
411
+ if (block.type === 'tool') gauge = addGrowth(gauge, block.name ?? SOURCES.tools, contentChars(block.state?.content))
412
+ else gauge = addGrowth(gauge, SOURCES.responses, contentChars(block))
413
+ }
414
+ }
415
+ }
416
+
417
+ return gauge.growth
418
+ }
package/store.ts CHANGED
@@ -3,7 +3,8 @@ import { access, mkdir, readdir, readFile, rename, stat, writeFile } from 'node:
3
3
  import { dirname } from 'node:path'
4
4
  import { loadProject, type Project, type Store } from './core/index'
5
5
 
6
- // The core's store over node's files and processes: an extension runs inside pi's own node process.
6
+ // The core's store over node's files and processes: pi runs an extension in its own node process, opencode a plugin
7
+ // in its server under Bun.
7
8
  export const nodeStore: Store = {
8
9
  read: path => readFile(path, 'utf8').catch(() => null),
9
10
  list: async (path, kind) => {