@meistrari/agent-core 0.1.2 → 0.1.3

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@meistrari/agent-core",
3
3
  "type": "module",
4
- "version": "0.1.2",
4
+ "version": "0.1.3",
5
5
  "packageManager": "bun@1.3.12",
6
6
  "description": "Shared contracts and runtime modules for Tela coding-agent sandboxes: agent protocol, supervisor wire protocol, resident supervisor, worker runtime client, and Claude/Codex harness adapters.",
7
7
  "license": "UNLICENSED",
@@ -111,6 +111,7 @@ export interface ClaudeEventMapperState {
111
111
  interrupt: { status: 'none' } | { status: 'requesting' | 'accepted', turnId: string }
112
112
  sessionState?: 'running' | 'idle'
113
113
  currentTurnId?: string
114
+ currentCommandId?: string
114
115
  currentMessageId?: string
115
116
  currentCompactionId?: string
116
117
  }
@@ -213,6 +214,7 @@ export function mapClaudeMessage(message: SDKMessage, state: ClaudeEventMapperSt
213
214
  state.turnStarted = false
214
215
  state.interrupt = { status: 'none' }
215
216
  state.currentTurnId = undefined
217
+ state.currentCommandId = undefined
216
218
  state.currentMessageId = undefined
217
219
  state.currentCompactionId = undefined
218
220
  return drafts
@@ -522,7 +524,7 @@ function ensureTurnStarted(drafts: AgentEventDraft[], state: ClaudeEventMapperSt
522
524
  state.currentTurnId = createRuntimeTurnId()
523
525
  state.currentMessageId = undefined
524
526
  state.contentBlockTypeByIndex.clear()
525
- drafts.push({ type: 'turn.started', turnId: state.currentTurnId, actor: mainActor, payload: {} })
527
+ drafts.push({ type: 'turn.started', turnId: state.currentTurnId, actor: mainActor, payload: removeUndefined({ commandId: state.currentCommandId }) })
526
528
  ensureSessionRunning(drafts, state)
527
529
  return state.currentTurnId
528
530
  }
@@ -95,6 +95,7 @@ export class ClaudeRun implements AgentRun {
95
95
  private finished = false
96
96
  private interruptRequest?: { turnId: string, promise: Promise<void> }
97
97
  private readonly acceptanceWaiters = new Map<string, AcceptanceWaiter>()
98
+ private readonly commandByClientMessageId = new Map<string, string>()
98
99
 
99
100
  constructor({ metadata, query, userInputRequests, input, eventMapperState, init }: ClaudeRunInput) {
100
101
  this.metadata = metadata
@@ -164,6 +165,7 @@ export class ClaudeRun implements AgentRun {
164
165
  // and a receipt with no registered waiter would be lost.
165
166
  const clientMessageId = deriveMessageId(command.commandId)
166
167
  const receipt = this.registerAcceptanceWaiter(clientMessageId)
168
+ this.commandByClientMessageId.set(clientMessageId, command.commandId)
167
169
  try {
168
170
  await this.deliverInput(message)
169
171
  // `submitted` requires the provider's positive acceptance receipt — the pinned
@@ -257,6 +259,7 @@ export class ClaudeRun implements AgentRun {
257
259
  }))
258
260
  }
259
261
  this.acceptanceWaiters.clear()
262
+ this.commandByClientMessageId.clear()
260
263
  this.events.push({ type: 'session.ended', payload: error ? { reason, error } : { reason } })
261
264
  this.events.push({ type: 'session.state.changed', payload: { state: reason === 'failed' ? 'failed' : 'stopped' } })
262
265
  this.events.end()
@@ -306,8 +309,17 @@ export class ClaudeRun implements AgentRun {
306
309
  this.acceptanceWaiters.get(parsed.data.command_uuid)?.reject(new AgentDeliveryUnknownError({
307
310
  message: `Claude command ended as ${parsed.data.state} before acceptance was observed.`,
308
311
  }))
312
+ this.commandByClientMessageId.delete(parsed.data.command_uuid)
309
313
  return
310
314
  }
315
+ // A queued receipt acknowledges admission, not turn ownership. Keep the
316
+ // mapping after acceptance settles: the provider's started receipt is
317
+ // the authority for the next root turn, even with several queued inputs.
318
+ if (parsed.data.state === 'started') {
319
+ this.eventMapperState.currentCommandId = this.commandByClientMessageId.get(parsed.data.command_uuid)
320
+ }
321
+ if (parsed.data.state === 'completed')
322
+ this.commandByClientMessageId.delete(parsed.data.command_uuid)
311
323
  this.acceptanceWaiters.get(parsed.data.command_uuid)?.resolve()
312
324
  }
313
325
 
@@ -399,8 +399,10 @@ function hookPromptText(item: CodexHookPromptItem): string | undefined {
399
399
  }
400
400
 
401
401
  function commandExecutionResult(item: Extract<CodexCompletedItem, { type: 'commandExecution' }>, status: 'completed' | 'failed'): AgentToolResult | undefined {
402
- const text = optionalNonEmpty(item.aggregatedOutput ?? undefined)
403
- if (!text)
402
+ // Stdout is content, not a label: whitespace and an explicitly empty
403
+ // successful output must survive normalization into the complete step.
404
+ const text = item.aggregatedOutput
405
+ if (typeof text !== 'string')
404
406
  return undefined
405
407
 
406
408
  return { success: status === 'completed', content: [{ type: 'text', text }] }
@@ -135,7 +135,7 @@ export const sessionEndedAgentEventSchema = agentEventBaseSchema.extend({
135
135
 
136
136
  export const turnStartedAgentEventSchema = agentTurnEventBaseSchema.extend({
137
137
  type: z.literal('turn.started'),
138
- payload: z.object({}).strict(),
138
+ payload: z.object({ commandId: z.string().min(1).optional() }).strict(),
139
139
  }).strict()
140
140
 
141
141
  export const turnEndedAgentEventSchema = agentTurnEventBaseSchema.extend({
@@ -1,6 +1,6 @@
1
1
  // Generated by scripts/write-provenance.ts. Do not edit by hand.
2
2
  export const generatedProvenance = {
3
- version: "0.1.2",
4
- sha: "85081b3dd3667033dfb1dfd399a6f59d3fd42d43",
5
- buildTime: "2026-09-09T11:47:21.679Z",
3
+ version: "0.1.3",
4
+ sha: "8b997b992439bb6300854fed35d461ca0fdbd3e2",
5
+ buildTime: "2026-09-09T19:31:26.657Z",
6
6
  } as const
@@ -23,6 +23,15 @@ export class DurableStepProjector {
23
23
  this.db.exec(`pragma journal_mode=WAL; pragma synchronous=FULL;
24
24
  create table if not exists steps(id text primary key, body text not null, last_event_id text);
25
25
  create table if not exists journal(id text primary key, event text, frames text);
26
+ create table if not exists turn_commands(
27
+ session_id text not null, provider_session_id text not null,
28
+ actor_id text not null, turn_id text not null, command_id text not null,
29
+ primary key(session_id, provider_session_id, actor_id, turn_id)
30
+ );
31
+ create index if not exists steps_tool_command on steps(
32
+ json_extract(body,'$.sessionId'), json_extract(body,'$.actor.actorId'),
33
+ json_extract(body,'$.kind'), json_extract(body,'$.sourceId')
34
+ );
26
35
  `)
27
36
  if (!this.db.query<{ name: string }, []>('pragma table_info(steps)').all().some(column => column.name === 'last_event_id'))
28
37
  this.db.exec('alter table steps add column last_event_id text')
@@ -76,6 +85,7 @@ export class DurableStepProjector {
76
85
  }
77
86
 
78
87
  private async project(event: AgentEvent): Promise<WireEventBody[]> {
88
+ const commandId = this.correlateCommand(event)
79
89
  const kind = event.type.startsWith('message.')
80
90
  ? 'message'
81
91
  : event.type.startsWith('tool.call.')
@@ -86,6 +96,8 @@ export class DurableStepProjector {
86
96
  if (event.type === 'turn.ended' || event.type === 'session.ended') {
87
97
  for (const row of this.db.query<{ body: string, last_event_id: string | null }, []>('select body, last_event_id from steps').all()) {
88
98
  const step = JSON.parse(row.body) as StepDetailV1
99
+ if (step.sessionId !== event.sessionId || step.providerSessionId !== event.providerSessionId)
100
+ continue
89
101
  if ((step.status !== 'running' && row.last_event_id !== event.eventId) || (event.type === 'turn.ended' && (step.turnId !== event.turnId || step.actor.actorId !== event.actor.actorId)))
90
102
  continue
91
103
  step.status = event.type === 'turn.ended' && event.payload.status === 'failed' ? 'failed' : 'interrupted'
@@ -109,7 +121,7 @@ export class DurableStepProjector {
109
121
  stepId,
110
122
  version: 1,
111
123
  provider: event.provider,
112
- commandId: typeof payload.commandId === 'string' ? payload.commandId : null,
124
+ commandId,
113
125
  role: kind === 'message' ? payload.role as StepSummary['role'] : null,
114
126
  toolName: typeof payload.toolName === 'string' ? payload.toolName : null,
115
127
  status: 'running',
@@ -121,6 +133,7 @@ export class DurableStepProjector {
121
133
  }
122
134
  if (step.status !== 'running' && row?.last_event_id !== event.eventId)
123
135
  return []
136
+ step.commandId ??= commandId
124
137
  if (event.type.endsWith('started')) {
125
138
  if (row && row.last_event_id !== event.eventId)
126
139
  return []
@@ -158,12 +171,16 @@ export class DurableStepProjector {
158
171
  }
159
172
 
160
173
  private async finish(step: StepDetailV1): Promise<WireEventBody[]> {
174
+ // The provider can correlate a turn after its first content start. A
175
+ // terminal fact must resolve that binding too, not only normal closes.
176
+ step.commandId ??= this.correlateCommand(step)
161
177
  if (step.kind === 'message') {
162
178
  // References, not repeated complete tool payloads, connect message content.
163
- step.content.toolSteps = this.db.query<{ id: string }, [string, string]>(`
179
+ step.content.toolSteps = this.db.query<{ id: string }, [string, string, string, string]>(`
164
180
  select id from steps where json_extract(body,'$.kind')='tool'
181
+ and json_extract(body,'$.sessionId')=? and json_extract(body,'$.providerSessionId')=?
165
182
  and json_extract(body,'$.turnId')=? and json_extract(body,'$.actor.actorId')=? order by rowid
166
- `).all(step.turnId, step.actor.actorId).map(row => row.id)
183
+ `).all(step.sessionId, step.providerSessionId, step.turnId, step.actor.actorId).map(row => row.id)
167
184
  }
168
185
  this.save(step)
169
186
  const body = serializeStepDetail(step)
@@ -179,6 +196,39 @@ export class DurableStepProjector {
179
196
  ]
180
197
  }
181
198
 
199
+ private correlateCommand(event: AgentEvent | StepDetailV1): string | null {
200
+ if (!('turnId' in event))
201
+ return null
202
+ const key = [event.sessionId, event.providerSessionId, event.actor.actorId, event.turnId] as const
203
+ const previous = this.db.query<{ command_id: string }, [string, string, string, string]>(
204
+ 'select command_id from turn_commands where session_id=? and provider_session_id=? and actor_id=? and turn_id=?',
205
+ ).get(...key)?.command_id
206
+ const payload = 'payload' in event ? event.payload as Record<string, unknown> : event
207
+ const explicit = typeof payload.commandId === 'string' ? payload.commandId : undefined
208
+ if (previous && explicit && previous !== explicit)
209
+ throw new Error('Conflicting command identity for a provider turn.')
210
+ let inherited: string | undefined
211
+ if (!previous && !explicit && event.actor.type === 'subagent') {
212
+ const toolCallId = event.actor.parentToolCallId
213
+ ?? (event.actor.origin.type === 'tool_call' ? event.actor.origin.toolCallId : undefined)
214
+ if (toolCallId) {
215
+ const parents = this.db.query<{ command_id: string }, [string, string, string]>(`
216
+ select distinct json_extract(body,'$.commandId') as command_id from steps
217
+ where json_extract(body,'$.sessionId')=? and json_extract(body,'$.actor.actorId')=?
218
+ and json_extract(body,'$.kind')='tool' and json_extract(body,'$.sourceId')=?
219
+ and json_extract(body,'$.commandId') is not null limit 2
220
+ `).all(event.sessionId, event.actor.parentActorId, toolCallId)
221
+ if (parents.length === 1)
222
+ inherited = parents[0]!.command_id
223
+ }
224
+ }
225
+ const commandId = previous ?? explicit ?? inherited
226
+ if (commandId && !previous) {
227
+ this.db.query('insert into turn_commands values (?,?,?,?,?)').run(...key, commandId)
228
+ }
229
+ return commandId ?? null
230
+ }
231
+
182
232
  private save(step: StepDetailV1): void {
183
233
  this.db.query('insert into steps(id,body,last_event_id) values (?,?,?) on conflict(id) do update set body=excluded.body,last_event_id=excluded.last_event_id')
184
234
  .run(step.stepId, JSON.stringify(step), this.currentEventId)