@iiiokojiadbi/shift 0.34.1 → 0.36.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/core/flows.ts CHANGED
@@ -313,8 +313,9 @@ export async function resumeShift(project: Project): Promise<{ text: string; pro
313
313
  return { text: `No letter.md in any folder of ${SHIFTS}/ — nothing to pick up.` }
314
314
  }
315
315
 
316
- // The records, the last shifts and the documents' remarks as they are now, for the message after a shift.
317
- async function handBack(project: Project, dir: string): Promise<HandedBack> {
316
+ // The records, the last shifts and the documents' remarks as they are now, for the message after a shift. A harness
317
+ // that carries the message into the replacement history reads them before the let-go, not after it.
318
+ export async function handBack(project: Project, dir: string): Promise<HandedBack> {
318
319
  return {
319
320
  work: await readRecords(project),
320
321
  knowledge: project.settings.knowledge,
@@ -390,8 +391,9 @@ export type LetGo = {
390
391
  after: number
391
392
  }
392
393
 
393
- // After the let-go: the summary and the outcome on disk, then continue or wait, as the agent asked.
394
- export async function settleShift(project: Project, letGo: LetGo): Promise<Settled> {
394
+ // After the let-go: the summary and the outcome on disk, then continue or wait, as the agent asked. `back` is what
395
+ // the message hands back, read before the let-go when the harness carries it into the replacement history.
396
+ export async function settleShift(project: Project, letGo: LetGo, back?: HandedBack): Promise<Settled> {
395
397
  const { store } = project
396
398
  const { shift, before, after } = letGo
397
399
  const summary = renderSummary(letGo.messages)
@@ -402,19 +404,19 @@ export async function settleShift(project: Project, letGo: LetGo): Promise<Settl
402
404
  `${shift.dir}/${NAMES.about}`,
403
405
  renderAbout({ ...shift, tokensBefore: before, tokensAfter: after, summaryChars: summary.length, result }),
404
406
  )
405
- const back = await handBack(project, shift.dir)
407
+ const handed = back ?? (await handBack(project, shift.dir))
406
408
  const name = basename(shift.dir)
407
409
 
408
- const files = deliveredFiles(back.work)
410
+ const files = deliveredFiles(handed.work)
409
411
  if (shift.after === 'continue') {
410
412
  await outcome(OUTCOME.continuing(shrank))
411
- const prompt = continuePrompt(shift.letter, back)
413
+ const prompt = continuePrompt(shift.letter, handed)
412
414
 
413
415
  return { after: 'continue', prompt, note: { context: prompt, dir: shift.dir, files }, row: CONTINUING(name, shrank, shift.dir) }
414
416
  }
415
417
 
416
418
  await outcome(OUTCOME.waiting(shrank, 'waiting for the owner'))
417
- const note = { context: waitContext(shift.letter, back), dir: shift.dir, files }
419
+ const note = { context: waitContext(shift.letter, handed), dir: shift.dir, files }
418
420
 
419
421
  return { after: 'wait', note, row: WAITING(name, shrank) }
420
422
  }
package/core/loop.ts CHANGED
@@ -1,9 +1,19 @@
1
1
  // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
- import { settleShift, shiftNotMade, shiftUnsettled } from './flows'
2
+ import { handBack, settleShift, shiftNotMade, shiftUnsettled } from './flows'
3
3
  import { type GaugeKeeper, offerHint, takeHint } from './hint'
4
4
  import { basename } from './paths'
5
5
  import type { Project } from './project'
6
- import { compactInstructions, FAILURE_NOTE, NOT_MADE_NOTE, ourWords, SHIFT_NOW, UNSETTLED_NOTE } from './texts/prompts'
6
+ import {
7
+ compactInstructions,
8
+ continuePrompt,
9
+ FAILURE_NOTE,
10
+ HELD_NOTE,
11
+ NOT_MADE_NOTE,
12
+ ourWords,
13
+ SHIFT_NOW,
14
+ UNSETTLED_NOTE,
15
+ WAKE,
16
+ } from './texts/prompts'
7
17
  import { DELIVERED, NOT_CONTINUED } from './texts/rows'
8
18
  import type { PendingShift, Settled, WaitNote } from './types'
9
19
 
@@ -17,10 +27,18 @@ export type LoopState = {
17
27
  // The letter and the records waiting for the owner's next message.
18
28
  note: WaitNote | null
19
29
  // A let-go in flight, and whether the owner spoke during it: their message found no letter yet, so the one the
20
- // shift then leaves for them is sent after it rather than kept for a message they already sent.
21
- letting?: { heard: boolean } | null
30
+ // shift then leaves for them is sent after it rather than kept for a message they already sent. A harness that can
31
+ // take the owner's message back holds it here instead, and one that can keep it in its hook waits for the shift's
32
+ // message as a note: either way it reaches the agent after the letter, never before it.
33
+ letting?: Letting | null
22
34
  }
23
35
 
36
+ // The let-go's own state: whether the owner spoke, their messages held, and how many wait in a harness's hook.
37
+ export type Letting = { heard: boolean; held?: HeldMessage[]; waiting?: number }
38
+
39
+ // An owner's message held back while a shift is under way; what it carried besides the text, as the harness gave it.
40
+ export type HeldMessage = { text: string; attachments?: readonly unknown[] }
41
+
24
42
  export type Level = 'info' | 'warning' | 'error'
25
43
 
26
44
  export type Loop = {
@@ -34,12 +52,15 @@ export type Loop = {
34
52
  export type LetGoHarness = {
35
53
  // How full the history is now; undefined before the first reading.
36
54
  fill(): Promise<number | undefined>
37
- // Lets the history go with the instructions: what it went into and the fills around it, or why it did not.
55
+ // Lets the history go with the instructions: what it went into and the fills around it, or why it did not. `carry`
56
+ // is the message a harness able to put it into the replacement history takes; `carried` says that it did, and then
57
+ // the message is never told again as the turn's prompt.
38
58
  letGo(
39
59
  instructions: string,
40
- ): Promise<{ messages: readonly { role: string; text: string }[]; before?: number; after?: number } | { skip: string }>
41
- // Starts the agent's next turn with the prompt.
42
- continueWith(prompt: string): Promise<void>
60
+ carry?: string,
61
+ ): Promise<{ messages: readonly { role: string; text: string }[]; before?: number; after?: number; carried?: boolean } | { skip: string }>
62
+ // Starts the agent's next turn with the prompt, and what the owner's held messages carried besides their text.
63
+ continueWith(prompt: string, attachments?: readonly unknown[]): Promise<void>
43
64
  // What the harness refreshes once the history is let go, before the message after it.
44
65
  afterLetGo?(): Promise<void>
45
66
  }
@@ -70,21 +91,26 @@ export async function loopOffer(loop: Loop, gauge: GaugeKeeper): Promise<{ text:
70
91
  export async function afterTurn(project: Project, loop: Loop, harness: LetGoHarness, aborted: boolean): Promise<void> {
71
92
  // The let-go is marked before the shift is claimed, so an owner's message never falls between the two: a harness may
72
93
  // keep them apart. Claimed in the change that clears it: two ends of a turn never let go twice.
73
- await loop.update(current => (current.pending === null ? current : { ...current, letting: { heard: current.letting?.heard === true } }))
94
+ await loop.update(current => (current.pending === null ? current : { ...current, letting: lettingOf(current) }))
74
95
  const claim: { shift?: PendingShift | null } = {}
75
96
  await loop.update(current => {
76
97
  claim.shift = current.pending
77
- return current.pending === null ? current : { ...current, pending: null, letting: { heard: current.letting?.heard === true } }
98
+ return current.pending === null ? current : { ...current, pending: null, letting: lettingOf(current) }
78
99
  })
79
100
  const { shift } = claim
80
101
  if (shift === undefined || shift === null) return
81
102
  try {
82
103
  await letGoShift(project, loop, harness, shift, aborted)
83
104
  } finally {
84
- await loop.update(current => (current.letting == null ? current : { ...current, letting: null }))
105
+ // Whatever way the shift ended, a message the owner sent meanwhile is never dropped with it.
106
+ await finish(loop, harness, '', { context: '', dir: shift.dir, files: [] })
85
107
  }
86
108
  }
87
109
 
110
+ function lettingOf(current: LoopState): Letting {
111
+ return { ...current.letting, heard: current.letting?.heard === true }
112
+ }
113
+
88
114
  async function letGoShift(project: Project, loop: Loop, harness: LetGoHarness, shift: PendingShift, aborted: boolean): Promise<void> {
89
115
  const before = await harness.fill().catch(() => undefined)
90
116
  const name = basename(shift.dir)
@@ -95,7 +121,12 @@ async function letGoShift(project: Project, loop: Loop, harness: LetGoHarness, s
95
121
  return
96
122
  }
97
123
 
98
- const done = await harness.letGo(compactInstructions(shift)).catch((error: unknown) => ({ skip: `the let-go failed: ${String(error)}` }))
124
+ // A continue shift's message is built before the let-go: a harness able to put it into the replacement history takes
125
+ // it there, so everything admitted after the compaction reads the letter first.
126
+ const back = shift.after === 'continue' ? await handBack(project, shift.dir).catch(() => null) : null
127
+ const done = await harness
128
+ .letGo(compactInstructions(shift), back === null ? undefined : continuePrompt(shift.letter, back))
129
+ .catch((error: unknown) => ({ skip: `the let-go failed: ${String(error)}` }))
99
130
  if ('skip' in done) {
100
131
  // The harness's reason, in the mod's words wherever it goes: the note, the row and about.md.
101
132
  const why = ourWords(done.skip)
@@ -106,12 +137,16 @@ async function letGoShift(project: Project, loop: Loop, harness: LetGoHarness, s
106
137
  let settled: Settled
107
138
  try {
108
139
  await harness.afterLetGo?.()
109
- settled = await settleShift(project, {
110
- shift,
111
- messages: done.messages,
112
- before: done.before ?? before,
113
- after: done.after ?? (await harness.fill()) ?? 0,
114
- })
140
+ settled = await settleShift(
141
+ project,
142
+ {
143
+ shift,
144
+ messages: done.messages,
145
+ before: done.before ?? before,
146
+ after: done.after ?? (await harness.fill()) ?? 0,
147
+ },
148
+ back ?? undefined,
149
+ )
115
150
  } catch (error) {
116
151
  const why = ourWords(String(error))
117
152
  loop.tell(await shiftUnsettled(project, shift, why, done.before ?? before), 'error')
@@ -127,40 +162,107 @@ async function letGoShift(project: Project, loop: Loop, harness: LetGoHarness, s
127
162
  // The shift is settled and written; a turn that does not start is told, not recorded against it, and its letter
128
163
  // waits for the owner's next message as after a wait. A letter an earlier shift left waiting is older than this one.
129
164
  await dropWaiting(loop).catch(() => undefined)
130
- await harness.continueWith(settled.prompt).catch(async (error: unknown) => {
131
- await loop.update(current => ({ ...current, note: settled.note }))
132
- loop.tell(NOT_CONTINUED(String(error)), 'error')
133
- })
165
+ // A message the harness carried is in the history already: the turn starts from one line, never the whole message
166
+ // told twice. A note kept for a turn that did not start carries that line too.
167
+ const carried = done.carried === true
168
+ const text = carried ? WAKE : settled.prompt
169
+ await finish(loop, harness, text, carried ? { ...settled.note, context: text } : settled.note)
134
170
  }
135
171
 
136
172
  // A failed shift is told to the agent, who was told it was accepted: at once when it was to continue and may go on,
137
173
  // otherwise with the owner's next message.
138
174
  async function tellAgent(loop: Loop, harness: LetGoHarness, shift: PendingShift, context: string, goOn: boolean): Promise<void> {
139
- if (goOn && shift.after === 'continue') {
140
- await harness.continueWith(context).catch(async (error: unknown) => {
141
- await loop.update(current => ({ ...current, note: { context, dir: shift.dir, files: [FAILURE_NOTE] } }))
142
- loop.tell(NOT_CONTINUED(String(error), FAILURE_NOTE), 'error')
143
- })
144
- return
145
- }
146
- await leave(loop, harness, { context, dir: shift.dir, files: [FAILURE_NOTE] })
175
+ const note = { context, dir: shift.dir, files: [FAILURE_NOTE] }
176
+ if (goOn && shift.after === 'continue') await finish(loop, harness, context, note)
177
+ else await leave(loop, harness, note)
147
178
  }
148
179
 
149
180
  // A note for the owner's next message — or, when the owner already spoke while the history was let go, sent after
150
181
  // that message at once; kept for the next one if it does not go.
151
182
  async function leave(loop: Loop, harness: LetGoHarness, note: WaitNote): Promise<void> {
152
- const heard: { now?: boolean } = {}
183
+ const heard = { now: false }
153
184
  await loop.update(current => {
154
185
  heard.now = current.letting?.heard === true
155
- return heard.now ? { ...current, letting: null } : { ...current, note, letting: null }
186
+ return heard.now ? current : { ...current, note, letting: null }
187
+ })
188
+ if (heard.now) await finish(loop, harness, note.context, note)
189
+ }
190
+
191
+ // The shift's last message, and the end of its let-go in the same change, so a message of the owner's after it is not
192
+ // held at all. The owner's held messages go after the prompt that starts the next turn; a turn that does not start
193
+ // keeps them with the note for the owner's next message. An owner's message waiting in the harness's hook takes the
194
+ // prompt itself, as a note, and goes after the let-go: started apart, the prompt would follow the owner's message.
195
+ async function finish(loop: Loop, harness: LetGoHarness, prompt: string, keep: WaitNote): Promise<void> {
196
+ const taken: { held: HeldMessage[]; waits: boolean } = { held: [], waits: false }
197
+ await loop.update(current => {
198
+ if (current.letting == null) return current
199
+ taken.held = current.letting.held ?? []
200
+ taken.waits = (current.letting.waiting ?? 0) > 0
201
+ const text = withHeld(prompt, taken.held)
202
+ return taken.waits && text !== '' ? { ...current, note: { ...keep, context: text }, letting: null } : { ...current, letting: null }
203
+ })
204
+ const text = withHeld(prompt, taken.held)
205
+ if (taken.waits || text === '') return
206
+ await harness.continueWith(text, attachmentsOf(taken.held)).catch(async (error: unknown) => {
207
+ const kept = { ...keep, context: withHeld(keep.context, taken.held) }
208
+ await loop.update(current => ({ ...current, note: kept }))
209
+ loop.tell(NOT_CONTINUED(String(error), keep.files.includes(FAILURE_NOTE) ? FAILURE_NOTE : undefined), 'error')
210
+ })
211
+ }
212
+
213
+ function withHeld(context: string, held: readonly HeldMessage[]): string {
214
+ if (held.length === 0) return context
215
+ const words = HELD_NOTE(held.map(message => message.text))
216
+
217
+ return context === '' ? words : `${context}\n\n${words}`
218
+ }
219
+
220
+ function attachmentsOf(held: readonly HeldMessage[]): readonly unknown[] | undefined {
221
+ const all = held.flatMap(message => message.attachments ?? [])
222
+
223
+ return all.length === 0 ? undefined : all
224
+ }
225
+
226
+ // The owner's message while a shift waits for its turn to end or lets the history go, from a harness that can take it
227
+ // back: held, to go after the letter, and true; false when no shift is under way and the message goes as it is.
228
+ export async function holdOwner(loop: Loop, message: HeldMessage): Promise<boolean> {
229
+ const held = { now: false }
230
+ await loop.update(current => {
231
+ held.now = current.pending !== null || current.letting != null
232
+ return held.now
233
+ ? { ...current, letting: { ...lettingOf(current), heard: true, held: [...(current.letting?.held ?? []), message] } }
234
+ : current
156
235
  })
157
- if (heard.now !== true) return
158
- await harness.continueWith(note.context).catch(async (error: unknown) => {
159
- await loop.update(current => ({ ...current, note }))
160
- loop.tell(NOT_CONTINUED(String(error), note.files.includes(FAILURE_NOTE) ? FAILURE_NOTE : undefined), 'error')
236
+
237
+ return held.now
238
+ }
239
+
240
+ // The owner's message while a shift is under way, from a harness that cannot take it back but can keep it in its hook
241
+ // until the shift is over: it then carries the shift's message, which waits for it as a note. The harness waits while
242
+ // `sleep` lets it, up to `limit` ms; true once the shift it waited for is over, false when none was under way or it
243
+ // gave up — the message then goes as it is, and the shift's message is sent on its own.
244
+ export async function awaitShift(loop: Loop, sleep: (ms: number) => Promise<void>, limit: number): Promise<boolean> {
245
+ const under = { now: false }
246
+ await loop.update(current => {
247
+ under.now = current.pending !== null || current.letting != null
248
+ return under.now ? { ...current, letting: { ...lettingOf(current), waiting: (current.letting?.waiting ?? 0) + 1 } } : current
161
249
  })
250
+ if (!under.now) return false
251
+ for (let waited = 0; waited < limit; waited += WAIT_STEP) {
252
+ const { pending, letting } = await loop.read()
253
+ if (pending === null && letting == null) return true
254
+ await sleep(WAIT_STEP)
255
+ }
256
+ await loop.update(current =>
257
+ current.letting == null
258
+ ? current
259
+ : { ...current, letting: { ...current.letting, waiting: Math.max(0, (current.letting.waiting ?? 1) - 1) } },
260
+ )
261
+ return false
162
262
  }
163
263
 
264
+ const WAIT_STEP = 250
265
+
164
266
  // The note waiting for the owner's message, if any, and what clears it once it went with that message: a failed
165
267
  // delivery keeps it for the next one.
166
268
  export async function waitingNote(loop: Loop): Promise<{ context: string; delivered: () => Promise<void> } | null> {
@@ -168,7 +270,9 @@ export async function waitingNote(loop: Loop): Promise<{ context: string; delive
168
270
  // The owner spoke while a shift waits to let the history go or lets it go: what it leaves for them follows their
169
271
  // message, whether an older letter goes with this one or not.
170
272
  if (pending !== null || letting != null)
171
- await loop.update(current => (current.pending === null && current.letting == null ? current : { ...current, letting: { heard: true } }))
273
+ await loop.update(current =>
274
+ current.pending === null && current.letting == null ? current : { ...current, letting: { ...current.letting, heard: true } },
275
+ )
172
276
  if (note === null) return null
173
277
 
174
278
  return {
@@ -208,6 +208,10 @@ export function continuePrompt(letter: string, back: HandedBack): string {
208
208
  return shiftMessage('Shift done. You continue from where you stopped.', letter, back, [GUIDE_KNOWN, `Continue from "${NEXT}".`])
209
209
  }
210
210
 
211
+ // The turn after a let-go whose message the harness already put into the replacement history: the letter, the board
212
+ // and the tasks are above this line, so only the turn has to be started, never the message told twice.
213
+ export const WAKE = `The shift is done and your letter is above. Continue from "${NEXT}".`
214
+
211
215
  export function waitContext(letter: string, back: HandedBack): string {
212
216
  return shiftMessage("You shifted and waited for the owner; the owner's message comes with this one.", letter, back, [GUIDE_KNOWN])
213
217
  }
@@ -277,5 +281,9 @@ export const UNSETTLED_NOTE = (name: string, why: string, dir: string) =>
277
281
  Shift ${name}: the history was let go, but the mod could not hand your records back — ${why}. Read the letter of this shift, ${dir}/${NAMES.letter} — the one it accepted, whatever ${LETTER} holds now — then ${BOARD} and ${TASK_LIST}, and continue from "${NEXT}".
278
282
  </${MOD}>`
279
283
 
284
+ // The owner's messages held back while the history was let go, after the letter: their words as they wrote them.
285
+ export const HELD_NOTE = (texts: readonly string[]) =>
286
+ `<${MOD} note="from the mod: the owner wrote while you shifted">The owner sent ${texts.length === 1 ? 'this message' : `these ${texts.length} messages`} while the history was let go; the mod held ${texts.length === 1 ? 'it' : 'them'} back to reach you after your letter. ${texts.length === 1 ? 'It goes' : 'They go'} first, before "${NEXT}".</${MOD}>\n\n${texts.join('\n\n')}`
287
+
280
288
  // What the owner's row names when a failure's note went with their message.
281
289
  export const FAILURE_NOTE = 'the note that the shift failed'
@@ -20,6 +20,8 @@ export const UNSETTLED = (name: string, why: string) =>
20
20
 
21
21
  export const DELIVERED = (files: readonly string[], dir: string) => `went with your message: ${files.join(', ')} — ${dir}/${NAMES.letter}`
22
22
 
23
+ export const HELD = 'your message waits for the shift: it goes to the agent after its letter, once the history is let go'
24
+
23
25
  export const NOT_CONTINUED = (why: string, carried = 'the letter') =>
24
26
  `the next turn did not start after the shift — ${why}; send any message to go on, ${carried} goes with it`
25
27
 
package/index.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  import { resolve } from 'node:path'
2
- import type { CompactionEntry, CompactionResult, ExtensionAPI, ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent'
2
+ import type {
3
+ CompactionEntry,
4
+ CompactionResult,
5
+ ExtensionAPI,
6
+ ExtensionContext,
7
+ InputEvent,
8
+ SessionEntry,
9
+ } from '@earendil-works/pi-coding-agent'
3
10
  import { estimateTokens, findCutPoint, SettingsManager } from '@earendil-works/pi-coding-agent'
4
11
  import type { TSchema } from 'typebox'
5
12
  import type { Courier, Gauge, GaugeKeeper, LetGoHarness, Looks, Loop, LoopState, Note, Project, WaitNote } from './core/index'
@@ -18,6 +25,8 @@ import {
18
25
  FRESH_LOOP,
19
26
  formatK,
20
27
  gaugeStatus,
28
+ HELD,
29
+ holdOwner,
21
30
  letGoGauge,
22
31
  MOD,
23
32
  RESUME_COMMAND,
@@ -148,10 +157,19 @@ export default function shift(pi: ExtensionAPI): void {
148
157
 
149
158
  // The owner's own input: only a message that starts a run takes the waiting letter with it. An extension's message
150
159
  // comes after any owner input another extension took without a run, so it clears what that left.
151
- pi.on('input', async (event, _ctx) => {
160
+ pi.on('input', async (event, ctx) => {
152
161
  if (!enabled) return
153
- if (event.source === 'extension') ownerTyped = false
154
- else if (event.streamingBehavior === undefined) ownerTyped = true
162
+ if (event.source === 'extension') {
163
+ ownerTyped = false
164
+ return
165
+ }
166
+ // While a shift waits for its run to end or lets the history go, the owner's message is held and goes after the
167
+ // letter: pi sends what was typed during the let-go as soon as it ends, before the letter. A command runs as it is.
168
+ if (!event.text.startsWith('/') && (await holdOwner(loopOf(ctx), { text: event.text, attachments: event.images }))) {
169
+ tell(ctx, HELD, 'info')
170
+ return { action: 'handled' as const }
171
+ }
172
+ if (event.streamingBehavior === undefined) ownerTyped = true
155
173
  })
156
174
 
157
175
  // The doctrine every run; between turns a hint, and after a wait the letter, follow the owner's message.
@@ -233,10 +251,14 @@ export default function shift(pi: ExtensionAPI): void {
233
251
  if (enabled && loop.pending !== null && event.reason === 'threshold') return { cancel: true }
234
252
  })
235
253
 
236
- // The shift lets go once the run has settled: compacting aborts whatever runs, so never from inside the turn.
254
+ // The shift lets go once the run has settled: compacting aborts whatever runs, so never from inside the turn. Not
255
+ // awaited: pi defers every prompt until its settled handlers return, so an owner's message sent during the let-go
256
+ // would come only after the shift is over, too late to be held, and run before the shift's message.
237
257
  pi.on('agent_settled', async (event, ctx) => {
238
258
  if (loop.pending === null) return
239
- await afterTurn(await projectAt(ctx.cwd), loopOf(ctx), letGoOf(ctx), event.aborted)
259
+ void projectAt(ctx.cwd)
260
+ .then(project => afterTurn(project, loopOf(ctx), letGoOf(ctx), event.aborted))
261
+ .catch((error: unknown) => tell(ctx, `the shift did not finish: ${String(error)}`, 'error'))
240
262
  })
241
263
 
242
264
  // Any compaction starts a new stretch; one the agent did not ask for is told to it at its next look.
@@ -287,8 +309,11 @@ export default function shift(pi: ExtensionAPI): void {
287
309
  }),
288
310
  })
289
311
  }).catch((error: unknown) => ({ skip: `did not start: ${String(error)}` })),
290
- continueWith: async prompt => {
291
- pi.sendMessage({ customType: MOD, content: prompt, display: true }, { triggerTurn: true })
312
+ continueWith: async (prompt, attachments) => {
313
+ // The images of the owner's held messages go with it as pi gave them.
314
+ const images = (attachments ?? []) as NonNullable<InputEvent['images']>
315
+ const content = images.length === 0 ? prompt : [{ type: 'text' as const, text: prompt }, ...images]
316
+ pi.sendMessage({ customType: MOD, content, display: true }, { triggerTurn: true })
292
317
  },
293
318
  }
294
319
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iiiokojiadbi/shift",
3
- "version": "0.34.1",
3
+ "version": "0.36.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",
package/server.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  afterTurn,
21
21
  afterWrite,
22
22
  atPrompt,
23
+ awaitShift,
23
24
  beforeTool,
24
25
  compactInstructions,
25
26
  contentChars,
@@ -29,6 +30,7 @@ import {
29
30
  FRESH_LOOKS,
30
31
  FRESH_LOOP,
31
32
  gaugeStatus,
33
+ HELD_NOTE,
32
34
  letGoGauge,
33
35
  MOD,
34
36
  RESUME_COMMAND,
@@ -65,6 +67,8 @@ const KEPT_TOKENS = 15_000
65
67
  const CHARS_PER_TOKEN = 4
66
68
  // The rows the owner sees above what the mod sends the agent.
67
69
  const CONTINUED = `${MOD}: the letter and the records`
70
+ // How long the owner's message waits for a shift's let-go before it goes as it is.
71
+ const HOLD_LIMIT = 10 * 60_000
68
72
 
69
73
  // What the plugin keeps of one session; the plugin is one per project, shared by its sessions.
70
74
  type Session = {
@@ -74,6 +78,9 @@ type Session = {
74
78
  loop: LoopState
75
79
  // The loop's last update, which the next one waits for.
76
80
  updating: Promise<void>
81
+ // The owner's last message through the prompt hook, which the next one waits for: messages held for a shift take its
82
+ // message once and keep their order.
83
+ prompting: Promise<void>
77
84
  gauge: Gauge
78
85
  looks: Looks
79
86
  // The last step's prompt size: the history as the model read it.
@@ -125,6 +132,7 @@ const plugin: Definition = {
125
132
  rows: [...startRows.splice(0), ...begun.rows],
126
133
  loop: { ...FRESH_LOOP, note, pending },
127
134
  updating: Promise.resolve(),
135
+ prompting: Promise.resolve(),
128
136
  gauge: FRESH_GAUGE,
129
137
  looks: FRESH_LOOKS,
130
138
  fill: undefined,
@@ -324,18 +332,34 @@ const plugin: Definition = {
324
332
  // The owner's message: what changed between turns, a hint, and after a wait the letter go with it.
325
333
  // The notes go in the owner's message itself: opencode's inbox takes a message of its own separately, before or after
326
334
  // the owner's, whether it steers or waits in the queue.
335
+ // While a shift is under way the owner's message waits here, before it enters the session: entered, it would run
336
+ // before the shift's message, which then takes it as a note and goes first.
327
337
  await ctx.session.hook('prompt', async event => {
328
338
  const project = once()
329
339
  if (await apart(event.sessionID, project)) return
330
340
  const { sessionID } = event
331
- const courier = courierOf(sessionID, project)
332
- await countGrowth(courier.gauge, SOURCES.owner, event.prompt.text.length)
333
- const told = await atPrompt(courier, { runStarts: !(await state(sessionID)).busy, owner: true })
334
- if (told.notes.length === 0) return
335
- const text = told.notes.join('\n\n')
336
- event.prompt.text = `${event.prompt.text}\n\n${text}`
337
- await countGrowth(courier.gauge, SOURCES.attachments, text.length)
338
- await told.delivered()
341
+ const session = await state(sessionID)
342
+ const turn = session.prompting.then(async () => {
343
+ const loop = loopOf(sessionID)
344
+ const { pending, letting } = await loop.read()
345
+ let held = false
346
+ if (pending !== null || letting != null) {
347
+ // Idle with a shift no let-go has claimed: its run's end was missed, and the message must not wait for it.
348
+ if (pending !== null && letting == null && !session.busy) void afterTurn(await project(), loop, letGoOf(sessionID), false)
349
+ held = await awaitShift(loop, ms => new Promise(done => setTimeout(done, ms)), HOLD_LIMIT)
350
+ }
351
+ const courier = courierOf(sessionID, project)
352
+ await countGrowth(courier.gauge, SOURCES.owner, event.prompt.text.length)
353
+ const told = await atPrompt(courier, { runStarts: !session.busy, owner: true })
354
+ if (told.notes.length === 0) return
355
+ const text = told.notes.join('\n\n')
356
+ // After a shift the owner's words follow its message, marked as held for it, as in the other harnesses.
357
+ event.prompt.text = held ? `${text}\n\n${HELD_NOTE([event.prompt.text])}` : `${event.prompt.text}\n\n${text}`
358
+ await countGrowth(courier.gauge, SOURCES.attachments, text.length)
359
+ await told.delivered()
360
+ })
361
+ session.prompting = turn.catch(() => undefined)
362
+ await turn
339
363
  })
340
364
 
341
365
  // Every note to the agent mid-run goes with a tool's result: what changed in the records around a tool of the agent,