Skip to content

Commit f402d5a

Browse files
committed
Resume a DSH Turn still awaiting its original Todo selection
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent aeb57d1 commit f402d5a

3 files changed

Lines changed: 185 additions & 3 deletions

File tree

‎packages/dsh-loopx-plugin/README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,15 @@ Turn or pause and start the Goal to renew the existing allowance. The label
567567
reflects the Driver's last verified quota decision and updates with the existing
568568
GoalBar watch. In-flight activity and an explicit Pause keep their usual labels.
569569

570+
A normal DSH completion can also leave the original Turn awaiting required
571+
Todo selection. For guarded Turns with that explicit requirement, the Driver
572+
reads the exact receipt before scheduling another automatic Turn. If selection
573+
is still owed, the Driver retries once with the original Turn identity. A second
574+
completed attempt that still owes selection shows the recovery status and waits.
575+
Pause and Start requests another attempt on the same Turn. A committed selection
576+
lets the Driver follow the ordinary scheduling path. Interactive human messages
577+
continue to use the native Session.
578+
570579
If DSH refuses the maintenance slot before admission starts, the Driver waits
571580
for `Agent.whenIdle()` and re-requests evaluation for that same Session. This
572581
wait uses no polling timer and is cancelled by Pause, human input, Session

‎packages/dsh-loopx-plugin/src/driver.ts‎

Lines changed: 108 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,10 @@ const HOST_SURFACE = 'deepseek-harness-native'
3030
const RESOLUTION_SCHEMA = 'loopx_thread_agent_binding_resolution_v0'
3131
const HEARTBEAT_SCHEMA = 'heartbeat_agent_input_v1'
3232
const CONTINUATION_SCHEMA = 'loopx_dsh_continuation_v0'
33+
const RECEIPT_READBACK_SCHEMA = 'quota_receipt_readback_v0'
3334
const DEFAULT_WAIT_MS = 5 * 60_000
3435
const MAX_WAIT_MS = 24 * 60 * 60_000
36+
const SELECTION_RECOVERY_COMPLETION_LIMIT = 2
3537

3638
type TimerHandle = unknown
3739
type ReservationPhase = 'queued' | 'claimed' | 'admitted' | 'retired'
@@ -46,12 +48,21 @@ interface Binding {
4648
readonly agentId: string
4749
}
4850

51+
interface SelectionTurn extends Binding {
52+
readonly turnInstanceId: string
53+
}
54+
55+
interface SelectionRecovery extends SelectionTurn {
56+
readonly completedAttempts: number
57+
}
58+
4959
interface LoopXContinuationMessageSource {
5060
readonly kind: 'loopx-continuation'
5161
readonly schemaVersion: typeof CONTINUATION_SCHEMA
5262
readonly goalId: string
5363
readonly agentId: string
5464
readonly turnInstanceId: string
65+
readonly selectionRequired?: true
5566
}
5667

5768
declare module '@deepseek-ai/dsh-llm' {
@@ -75,6 +86,8 @@ interface ActivationProjection {
7586
readonly session: Agent['session']
7687
readonly pendingModelCalls: Set<string>
7788
activated: boolean
89+
hostTurn?: { turn: number; entered: boolean; selection?: SelectionTurn } | undefined
90+
pendingSelection?: SelectionRecovery | undefined
7891
}
7992

8093
interface EvaluationWaiter {
@@ -98,13 +111,15 @@ interface DriverState {
98111
timer?: TimerHandle | undefined
99112
reservation?: Reservation | undefined
100113
recoveryAttention?: Binding | undefined
114+
retrySelection: boolean
101115
}
102116

103117
interface QueuePlan extends Binding {
104118
readonly kind: 'queue'
105119
readonly session: Agent['session']
106120
readonly turnInstanceId: string
107121
readonly taskBody: string
122+
readonly selectionRequired: boolean
108123
}
109124

110125
interface WaitPlan {
@@ -154,12 +169,14 @@ const systemClock: DriverClock = Object.freeze({
154169
function continuationSource(
155170
message: UserMessage,
156171
): LoopXContinuationMessageSource | undefined {
157-
const source = exactRecord(message.source, [
172+
const observed = record(message.source)
173+
const source = exactRecord(observed, [
158174
'kind',
159175
'schemaVersion',
160176
'goalId',
161177
'agentId',
162178
'turnInstanceId',
179+
...(observed?.selectionRequired === true ? ['selectionRequired'] : []),
163180
])
164181
return source?.kind === 'loopx-continuation'
165182
&& source.schemaVersion === CONTINUATION_SCHEMA
@@ -207,6 +224,7 @@ function automaticMessage(
207224
goalId: plan.goalId,
208225
agentId: plan.agentId,
209226
turnInstanceId: plan.turnInstanceId,
227+
...(plan.selectionRequired ? { selectionRequired: true as const } : {}),
210228
}),
211229
})
212230
}
@@ -304,17 +322,52 @@ function foldActivationEvent(
304322
}
305323
}
306324

325+
function foldSelectionEvent(projection: ActivationProjection, event: SessionEvent): void {
326+
if (event.type === 'turn/start') {
327+
projection.hostTurn = { turn: event.data.turn, entered: false }
328+
return
329+
}
330+
const hostTurn = projection.hostTurn
331+
if (hostTurn === undefined) return
332+
if (event.type === 'user/message') {
333+
const source = continuationSource(event.data)
334+
if (source?.selectionRequired === true) {
335+
hostTurn.selection = { goalId: source.goalId, agentId: source.agentId,
336+
turnInstanceId: source.turnInstanceId }
337+
}
338+
} else if (event.type === 'step/start' && hostTurn.turn === event.data.turn) {
339+
hostTurn.entered = true
340+
} else if (event.type === 'turn/end' && hostTurn.turn === event.data.turn) {
341+
projection.hostTurn = undefined
342+
if (event.data.reason.kind === 'completed' && hostTurn.entered && hostTurn.selection !== undefined) {
343+
const selection = hostTurn.selection
344+
const previous = projection.pendingSelection
345+
const sameOriginal = previous?.turnInstanceId === selection.turnInstanceId
346+
&& previous.goalId === selection.goalId && previous.agentId === selection.agentId
347+
projection.pendingSelection = {
348+
...selection,
349+
completedAttempts: sameOriginal ? previous.completedAttempts + 1 : 1,
350+
}
351+
}
352+
}
353+
}
354+
307355
function foldSessionActivation(session: Agent['session']): ActivationProjection {
308356
const projection: ActivationProjection = {
309357
session,
310358
pendingModelCalls: new Set(),
311359
activated: false,
312360
}
313361
try {
314-
for (const event of session.snapshotEvents()) foldActivationEvent(projection, event)
362+
for (const event of session.snapshotEvents()) {
363+
foldActivationEvent(projection, event)
364+
foldSelectionEvent(projection, event)
365+
}
315366
} catch {
316367
projection.pendingModelCalls.clear()
317368
projection.activated = false
369+
projection.hostTurn = undefined
370+
projection.pendingSelection = undefined
318371
}
319372
return projection
320373
}
@@ -683,6 +736,7 @@ export class LoopXContinuationDriver {
683736
state.competing = inboxHasPending(agent.inbox)
684737
state.pauseAfterTurnError = false
685738
state.recoveryAttention = undefined
739+
state.retrySelection = false
686740
state.schedulerToken = ''
687741
state.unchangedPolls = 0
688742
state.commands.clear()
@@ -753,6 +807,7 @@ export class LoopXContinuationDriver {
753807
if (!state.activation.activated) return { kind: 'applied' }
754808

755809
state.pauseAfterTurnError = false
810+
state.retrySelection = state.activation.pendingSelection !== undefined
756811
const evaluated = new Promise<boolean>(resolve => {
757812
state.evaluationWaiters.add({ session: capture.session, resolve })
758813
})
@@ -785,6 +840,7 @@ export class LoopXContinuationDriver {
785840
if (reservation?.phase === 'claimed' || reservation?.phase === 'admitted') {
786841
reservation.preserveAcrossPause = true
787842
}
843+
state.retrySelection = false
788844
this.cancelPending(state)
789845
return this.captureIsLive(capture)
790846
&& state.activation.session === capture.session
@@ -798,6 +854,7 @@ export class LoopXContinuationDriver {
798854
const state = this.stateFor(agent)
799855
const wasActivated = state.activation.activated
800856
foldActivationEvent(state.activation, event)
857+
foldSelectionEvent(state.activation, event)
801858
if (!wasActivated && state.activation.activated
802859
&& agent.status === 'idle' && !state.pauseAfterTurnError) {
803860
this.requestEvaluation(state)
@@ -938,6 +995,7 @@ export class LoopXContinuationDriver {
938995
existing.competing = inboxHasPending(agent.inbox)
939996
existing.pauseAfterTurnError = false
940997
existing.recoveryAttention = undefined
998+
existing.retrySelection = false
941999
existing.schedulerToken = ''
9421000
existing.unchangedPolls = 0
9431001
existing.commands.clear()
@@ -952,6 +1010,7 @@ export class LoopXContinuationDriver {
9521010
stopping: false,
9531011
competing: inboxHasPending(agent.inbox),
9541012
pauseAfterTurnError: false,
1013+
retrySelection: false,
9551014
schedulerToken: '',
9561015
unchangedPolls: 0,
9571016
commands: new Set(),
@@ -1143,8 +1202,26 @@ export class LoopXContinuationDriver {
11431202
return { kind: 'wait', schedulerToken: '', unchangedPolls: 0 }
11441203
}
11451204

1146-
const turnInstanceId = this.makeTurnInstanceId()
11471205
setStage('quota')
1206+
const selection = state.activation.pendingSelection
1207+
let turnInstanceId: string | undefined
1208+
if (selection !== undefined
1209+
&& selection.goalId === binding.goalId && selection.agentId === binding.agentId) {
1210+
const receipt = await this.readSelectionReceipt(command, state.agent, selection, signal)
1211+
this.ensureReady(state, signal, session)
1212+
if (receipt.selection_required === true && receipt.settlement_binding_owed === true) {
1213+
if (!state.retrySelection && selection.completedAttempts >= SELECTION_RECOVERY_COMPLETION_LIMIT) {
1214+
return { kind: 'wait', recoveryAttention: binding }
1215+
}
1216+
turnInstanceId = selection.turnInstanceId
1217+
} else {
1218+
state.activation.pendingSelection = undefined
1219+
}
1220+
} else {
1221+
state.activation.pendingSelection = undefined
1222+
}
1223+
state.retrySelection = false
1224+
turnInstanceId ??= this.makeTurnInstanceId()
11481225
const quota = await this.readQuota(command, state.agent, binding, turnInstanceId, { signal })
11491226
this.ensureReady(state, signal, session)
11501227
if (quota.ok !== true) {
@@ -1195,12 +1272,15 @@ export class LoopXContinuationDriver {
11951272
false,
11961273
)
11971274
}
1275+
const receipt = record(quota.heartbeat_receipt)
11981276
return {
11991277
kind: 'queue',
12001278
...binding,
12011279
session,
12021280
turnInstanceId,
12031281
taskBody: taskBodyWithRewardMemory(taskBody, quota),
1282+
selectionRequired: (receipt?.status === 'committed' || receipt?.status === 'replayed')
1283+
&& receipt.selection_required === true && receipt.settlement_binding_owed === true,
12041284
}
12051285
}
12061286

@@ -1338,6 +1418,31 @@ export class LoopXContinuationDriver {
13381418
return decision
13391419
}
13401420

1421+
private async readSelectionReceipt(
1422+
command: LoopXCommand,
1423+
agent: Agent,
1424+
selection: SelectionTurn,
1425+
signal: AbortSignal,
1426+
): Promise<Record<string, unknown>> {
1427+
const readback = await runJsonCommand(command, [
1428+
'--registry', '.loopx/registry.json', '--format', 'json', 'quota', 'receipt',
1429+
'--goal-id', selection.goalId, '--agent-id', selection.agentId,
1430+
'--turn-instance-id', selection.turnInstanceId,
1431+
], { runner: this.runner, cwd: agent.session.header.cwd, signal })
1432+
const receipt = record(readback.heartbeat_receipt)
1433+
const identity = record(receipt?.settlement_identity)
1434+
if (readback.schema_version !== RECEIPT_READBACK_SCHEMA
1435+
|| readback.ok !== true || readback.goal_id !== selection.goalId
1436+
|| readback.agent_id !== selection.agentId || readback.turn_instance_id !== selection.turnInstanceId
1437+
|| receipt?.status !== 'committed' || receipt.turn_instance_id !== selection.turnInstanceId
1438+
|| !(receipt.selection_required === true && receipt.settlement_binding_owed === true
1439+
|| identity?.goal_id === selection.goalId && identity.agent_id === selection.agentId
1440+
&& identity.turn_instance_id === selection.turnInstanceId)) {
1441+
throw new LoopXCliError('invalid_schema', 'LoopX could not verify the original Turn selection', false)
1442+
}
1443+
return receipt
1444+
}
1445+
13411446
private readHeartbeat(
13421447
command: LoopXCommand,
13431448
agent: Agent,

‎packages/dsh-loopx-plugin/tests/driver.spec.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,6 +2057,74 @@ describe('same-session LoopX driver', () => {
20572057
})
20582058

20592059
describe('GoalBar exact-Session Driver bridge', () => {
2060+
it.each(['unfinished', 'bound', 'different-agent', 'no-step', 'one-completion'] as const)(
2061+
'reconciles an original selection after Host completion on restore (%s)', async variant => {
2062+
const host = fakeAgent()
2063+
const original = 'dsh-prior-original-turn'
2064+
const source = {
2065+
kind: 'loopx-continuation', schemaVersion: 'loopx_dsh_continuation_v0',
2066+
goalId, agentId, turnInstanceId: original, selectionRequired: true,
2067+
} as const
2068+
host.appendEvent(userSkillInvocationEvent())
2069+
const completed = variant === 'unfinished' ? 2 : 1
2070+
for (let turn = 0; turn < completed; turn += 1) {
2071+
host.appendEvent(sessionEvent('turn/start', { turn }))
2072+
host.appendEvent(sessionEvent('user/message', {
2073+
...userMessage('Continue the original Turn.'), source,
2074+
}))
2075+
if (variant !== 'no-step') host.appendEvent(sessionEvent('step/start', { turn, step: 0 }))
2076+
host.appendEvent(sessionEvent('turn/end', { turn, reason: { kind: 'completed' } }))
2077+
}
2078+
const fixture = runnerFixture()
2079+
const observed: string[] = []
2080+
const runner: FileRunner = async (file, args, options) => {
2081+
if (!args.includes('receipt')) return fixture.runner(file, args, options)
2082+
observed.push(args[args.indexOf('--turn-instance-id') + 1] ?? '')
2083+
const identity = { goal_id: goalId, agent_id: agentId, turn_instance_id: original }
2084+
return {
2085+
exitCode: 0, stderr: '', stdout: JSON.stringify({
2086+
ok: true, schema_version: 'quota_receipt_readback_v0', ...identity,
2087+
agent_id: variant === 'different-agent' ? 'agent-other' : agentId,
2088+
heartbeat_receipt: { status: 'committed', turn_instance_id: original,
2089+
...(variant === 'bound' ? { settlement_identity: identity } : {
2090+
selection_required: true, settlement_binding_owed: true,
2091+
}),
2092+
},
2093+
}),
2094+
}
2095+
}
2096+
const driver = new LoopXContinuationDriver({
2097+
isLiveAgent: agent => agent === host.agent, runner, makeTurnInstanceId: () => 'fresh-turn',
2098+
})
2099+
const capture = { agent: host.agent, session: host.agent.session }
2100+
try {
2101+
driver.observeAgent(host.agent)
2102+
if (variant === 'no-step' || variant === 'bound' || variant === 'one-completion') {
2103+
await waitFor(() => host.nextTurn.length === 1)
2104+
expect(observed).toEqual(variant === 'no-step' ? [] : [original])
2105+
expect(fixture.quotaCalls[0]).toContain(variant === 'one-completion' ? original : 'fresh-turn')
2106+
} else {
2107+
await waitFor(() => observed.length === 1)
2108+
const exactBinding = { goalId, loopxAgentId: agentId }
2109+
if (variant === 'unfinished') {
2110+
await waitFor(() => driver.hasRecoveryAttention(capture, exactBinding))
2111+
expect(fixture.quotaCalls).toHaveLength(0)
2112+
expect(host.nextTurn).toHaveLength(0)
2113+
await driver.evaluateActivatedSession(capture)
2114+
await waitFor(() => host.nextTurn.length === 1)
2115+
expect(fixture.quotaCalls[0]).toContain(original)
2116+
expect(observed).toEqual([original, original])
2117+
} else {
2118+
await driver.dispose()
2119+
expect(fixture.quotaCalls).toHaveLength(0)
2120+
}
2121+
}
2122+
} finally {
2123+
await driver.dispose()
2124+
}
2125+
},
2126+
)
2127+
20602128
it('projects only the observed Core recovery hold for the current binding', async () => {
20612129
const host = fakeAgent()
20622130
let recoveryState = 'attention_required'

0 commit comments

Comments
 (0)