@parall/daemon 1.64.0 → 1.65.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.
@@ -52231,6 +52231,7 @@ function projectRuntimeEvent(event, groupKey) {
52231
52231
  return { ...event, project: false, groupKey };
52232
52232
  case "runtime_session":
52233
52233
  case "turn_outcome":
52234
+ case "observation":
52234
52235
  return event;
52235
52236
  default:
52236
52237
  return { ...event, groupKey };
@@ -52247,6 +52248,81 @@ function describeRuntimeTurnTrigger(trigger) {
52247
52248
  }
52248
52249
  }
52249
52250
 
52251
+ // ts/agent-core/dist/runtime-observation.js
52252
+ import { randomUUID } from "node:crypto";
52253
+
52254
+ // ts/agent-core/dist/redact.js
52255
+ function redactSecrets(s, knownValues = []) {
52256
+ return maskKnownValues(s, knownValues).replace(/\b(agk|mck|cpk)_[A-Za-z0-9_-]+/g, "$1_***").replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "$1-***").replace(/\bAKIA[0-9A-Z]{16}\b/g, "AKIA***").replace(/\b((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+/gi, "$1***").replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization)["']?\s*[=:]\s*)(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s&;,}\]"']+)/gi, "$1***").replace(/[A-Za-z0-9_-]{32,}/g, "***");
52257
+ }
52258
+ function maskKnownValues(s, knownValues) {
52259
+ let out = s;
52260
+ for (const v of knownValues) {
52261
+ if (typeof v === "string" && v.length >= 6)
52262
+ out = out.split(v).join("***");
52263
+ }
52264
+ return out;
52265
+ }
52266
+ function redactTurnOutcome(event, knownValues) {
52267
+ const redacted = { ...event };
52268
+ if (redacted.detail)
52269
+ redacted.detail = redactSecrets(redacted.detail, knownValues);
52270
+ if (redacted.raw) {
52271
+ redacted.raw = Object.fromEntries(Object.entries(redacted.raw).map(([k, v]) => [
52272
+ k,
52273
+ typeof v === "string" ? redactSecrets(v, knownValues) : v
52274
+ ]));
52275
+ }
52276
+ return redacted;
52277
+ }
52278
+ function describeTurnOutcomeFailure(outcome) {
52279
+ const retryNote = outcome.retryAt ? `, retry at ${outcome.retryAt}` : "";
52280
+ return {
52281
+ warn: `${outcome.outcome}${retryNote}${outcome.detail ? ` \u2014 ${outcome.detail}` : ""}`,
52282
+ stepMessage: `LLM turn ${outcome.outcome}${retryNote}${outcome.detail ? `: ${outcome.detail}` : ""}`
52283
+ };
52284
+ }
52285
+ function redactLogger(log2, knownValues) {
52286
+ if (!log2)
52287
+ return void 0;
52288
+ return {
52289
+ info: (message) => log2.info(redactSecrets(message, knownValues)),
52290
+ warn: (message) => log2.warn(redactSecrets(message, knownValues)),
52291
+ error: (message) => log2.error(redactSecrets(message, knownValues)),
52292
+ ...log2.child ? { child: (name) => redactLogger(log2.child(name), knownValues) } : {}
52293
+ };
52294
+ }
52295
+
52296
+ // ts/agent-core/dist/runtime-observation.js
52297
+ function runtimeObservation(runtimeSessionId, content) {
52298
+ return {
52299
+ type: "observation",
52300
+ observationId: randomUUID(),
52301
+ runtimeSessionId,
52302
+ content: { ...content, observed_at: (/* @__PURE__ */ new Date()).toISOString() }
52303
+ };
52304
+ }
52305
+ function observationField(value) {
52306
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= 256 ? value : void 0;
52307
+ }
52308
+ async function persistRuntimeObservation(persister, sessionId, target, event, log2, knownSecrets = []) {
52309
+ const native = event.content.native && Object.fromEntries(Object.entries(event.content.native).map(([key, value]) => [
52310
+ key,
52311
+ typeof value !== "string" ? value : key.endsWith("_id") ? maskKnownValues(value, knownSecrets) : redactSecrets(value, knownSecrets)
52312
+ ]));
52313
+ try {
52314
+ await persister.persist(sessionId, "observation", {
52315
+ step_type: "observation",
52316
+ ...target,
52317
+ idempotency_key: `observation:${event.observationId}`,
52318
+ content: { ...event.content, ...native ? { native } : {} },
52319
+ projection: false
52320
+ });
52321
+ } catch (err) {
52322
+ log2?.warn(`runtime observation could not be saved for ${sessionId}: ${String(err)}`);
52323
+ }
52324
+ }
52325
+
52250
52326
  // ts/agent-core/dist/fork-prefix.js
52251
52327
  function sanitizeMeta(value) {
52252
52328
  return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
@@ -52285,6 +52361,108 @@ function buildForkResultPrefix(results) {
52285
52361
  return blocks.join("\n\n") + "\n\n---\n\n";
52286
52362
  }
52287
52363
 
52364
+ // ts/agent-core/dist/gateway-runtime-step.js
52365
+ import { randomUUID as randomUUID2 } from "node:crypto";
52366
+ async function createRuntimeStep(host, sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2) {
52367
+ switch (runtimeEvent.type) {
52368
+ case "observation":
52369
+ await persistRuntimeObservation(host.stepPersister, sessionId, target, runtimeEvent, host.opts?.log, host.opts?.config ? [host.opts.config.api_key] : []);
52370
+ break;
52371
+ case "thinking":
52372
+ await host.stepPersister.persist(sessionId, "thinking", {
52373
+ step_type: "thinking",
52374
+ target_type: target.target_type,
52375
+ target_id: target.target_id,
52376
+ idempotency_key: randomUUID2(),
52377
+ content: { text: runtimeEvent.text },
52378
+ group_key: runtimeEvent.groupKey
52379
+ });
52380
+ break;
52381
+ case "text":
52382
+ await host.stepPersister.persist(sessionId, "text", {
52383
+ step_type: "text",
52384
+ target_type: target.target_type,
52385
+ target_id: target.target_id,
52386
+ idempotency_key: randomUUID2(),
52387
+ content: {
52388
+ text: runtimeEvent.text,
52389
+ suppressed: runtimeEvent.project !== true
52390
+ },
52391
+ projection: runtimeEvent.project === true,
52392
+ group_key: runtimeEvent.groupKey
52393
+ });
52394
+ break;
52395
+ case "tool_call": {
52396
+ const step = await host.stepPersister.persist(sessionId, "tool_call", {
52397
+ step_type: "tool_call",
52398
+ target_type: target.target_type,
52399
+ target_id: target.target_id,
52400
+ // call_id is session-unique for bridge runtimes (server-enforced),
52401
+ // so the bare form anchors the tool step pair across retries —
52402
+ // unlike parel's turn-scoped `tc:{turnId}:{callId}` (see
52403
+ // protocol-vectors/agent-steps.json).
52404
+ idempotency_key: `tc:${runtimeEvent.callId}`,
52405
+ content: {
52406
+ call_id: runtimeEvent.callId,
52407
+ tool_name: runtimeEvent.toolName,
52408
+ tool_input: runtimeEvent.input,
52409
+ status: "running",
52410
+ started_at: runtimeEvent.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
52411
+ },
52412
+ group_key: runtimeEvent.groupKey,
52413
+ runtime_key: runtimeEvent.callId
52414
+ });
52415
+ if (step) {
52416
+ if (contextFilePath) {
52417
+ host.updateContextFileStepId(contextFilePath, step.id);
52418
+ } else if (stepIdFilePath) {
52419
+ host.writeStepIdFile(stepIdFilePath, step.id);
52420
+ }
52421
+ if (laneContextFilePath2) {
52422
+ host.updateContextFileStepId(laneContextFilePath2, step.id);
52423
+ }
52424
+ }
52425
+ break;
52426
+ }
52427
+ case "tool_result":
52428
+ await host.stepPersister.persist(sessionId, "tool_result", {
52429
+ step_type: "tool_result",
52430
+ target_type: target.target_type,
52431
+ target_id: target.target_id,
52432
+ idempotency_key: `tr:${runtimeEvent.callId}`,
52433
+ content: {
52434
+ call_id: runtimeEvent.callId,
52435
+ tool_name: runtimeEvent.toolName,
52436
+ status: runtimeEvent.error ? "error" : "success",
52437
+ output: runtimeEvent.output,
52438
+ duration_ms: runtimeEvent.durationMs ?? 0,
52439
+ collapsible: true
52440
+ },
52441
+ group_key: runtimeEvent.groupKey
52442
+ });
52443
+ if (contextFilePath) {
52444
+ host.updateContextFileStepId(contextFilePath, null);
52445
+ } else if (stepIdFilePath) {
52446
+ host.clearStepIdFile(stepIdFilePath);
52447
+ }
52448
+ if (laneContextFilePath2) {
52449
+ host.updateContextFileStepId(laneContextFilePath2, null);
52450
+ }
52451
+ break;
52452
+ case "error":
52453
+ await host.stepPersister.persist(sessionId, "error", {
52454
+ step_type: "text",
52455
+ target_type: target.target_type,
52456
+ target_id: target.target_id,
52457
+ idempotency_key: randomUUID2(),
52458
+ content: buildErrorStepContent(runtimeEvent.message),
52459
+ projection: false,
52460
+ group_key: runtimeEvent.groupKey
52461
+ });
52462
+ break;
52463
+ }
52464
+ }
52465
+
52288
52466
  // ts/agent-core/dist/dispatch-recovery.js
52289
52467
  var DispatchRecovery = class {
52290
52468
  scan;
@@ -52344,7 +52522,7 @@ function splitChangeSource(sourceId) {
52344
52522
  // ts/agent-core/dist/gateway-base.js
52345
52523
  import * as fs4 from "node:fs";
52346
52524
  import * as path5 from "node:path";
52347
- import { randomUUID as randomUUID2 } from "node:crypto";
52525
+ import { randomUUID as randomUUID4 } from "node:crypto";
52348
52526
 
52349
52527
  // ts/sdk/dist/browser-viewer.js
52350
52528
  var BROWSER_VIEWER_READINESS_TIMEOUT_MS = 6e4;
@@ -52357,6 +52535,20 @@ function browserViewerRequestOptions(command, opts) {
52357
52535
  };
52358
52536
  }
52359
52537
 
52538
+ // ts/sdk/dist/slack-endpoints.js
52539
+ function slackEndpoints(apiBase) {
52540
+ return {
52541
+ SLACK_CHANNELS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/channels`,
52542
+ SLACK_USERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/users`,
52543
+ SLACK_REPLIES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/replies`,
52544
+ SLACK_HISTORY: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/history`,
52545
+ SLACK_MEMBERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/members`,
52546
+ SLACK_STATUS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/status`,
52547
+ SLACK_FILE: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/file`,
52548
+ SLACK_FILES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/files`
52549
+ };
52550
+ }
52551
+
52360
52552
  // ts/sdk/dist/clip-connection-endpoints.js
52361
52553
  var clipConnectionEndpoints = {
52362
52554
  ORG_CLIP_MCP_OAUTH_ATTEMPT: (orgId, clipId, attemptId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-oauth-attempts/${attemptId}`,
@@ -52685,13 +52877,7 @@ var ENDPOINTS = {
52685
52877
  // Tier-B platform verb (agent-only): send one message as the bound bot.
52686
52878
  CHANNEL_SEND: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/channel-send`,
52687
52879
  // Tier-B read verbs (agent-only): workspace visibility as the bot sees it.
52688
- SLACK_CHANNELS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/channels`,
52689
- SLACK_USERS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/users`,
52690
- SLACK_HISTORY: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/history`,
52691
- SLACK_MEMBERS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/members`,
52692
- SLACK_STATUS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/status`,
52693
- SLACK_FILE: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/file`,
52694
- SLACK_FILES: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/files`,
52880
+ ...slackEndpoints(API_BASE2),
52695
52881
  // WeChat tier-B read verbs (agent-only; internal research preview).
52696
52882
  ...wechatEndpoints(API_BASE2),
52697
52883
  // Invitations (org-scoped, admin)
@@ -53373,14 +53559,16 @@ var SlackFilesClient = class extends AttachmentClient {
53373
53559
  }
53374
53560
  /**
53375
53561
  * Tier-B file upload verb (agent-only): share a file into a Slack
53376
- * conversation this connection has seen inbound, with the same
53377
- * reply-anchor contract as the text send.
53562
+ * conversation or thread with the same addressing as text sends.
53563
+ * Native threadTs requires a server supporting Slack thread sends.
53378
53564
  */
53379
53565
  async sendSlackFile(orgId, input) {
53380
53566
  const fd = new FormData();
53381
53567
  fd.append("conversation_id", input.conversationId);
53382
53568
  if (input.replyTo)
53383
53569
  fd.append("reply_to", input.replyTo);
53570
+ if (input.threadTs)
53571
+ fd.append("thread_ts", input.threadTs);
53384
53572
  if (input.text)
53385
53573
  fd.append("text", input.text);
53386
53574
  fd.append("file", input.content, input.fileName);
@@ -53388,8 +53576,48 @@ var SlackFilesClient = class extends AttachmentClient {
53388
53576
  }
53389
53577
  };
53390
53578
 
53579
+ // ts/sdk/dist/slack-read-client.js
53580
+ var SlackReadClient = class extends SlackFilesClient {
53581
+ slackReadQuery(base, query, extra) {
53582
+ const params = new URLSearchParams();
53583
+ if (query?.cursor)
53584
+ params.set("cursor", query.cursor);
53585
+ if (query?.limit)
53586
+ params.set("limit", String(query.limit));
53587
+ for (const [k, v] of Object.entries(extra ?? {}))
53588
+ params.set(k, v);
53589
+ const qs = params.toString();
53590
+ return qs ? `${base}?${qs}` : base;
53591
+ }
53592
+ /**
53593
+ * Tier-B read verbs (agent-only): workspace visibility as the bot sees
53594
+ * it. Same live gate as the send verb; authorization beyond it is the
53595
+ * bot's own Slack permissions.
53596
+ */
53597
+ async listSlackChannels(orgId, query) {
53598
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_CHANNELS(orgId), query));
53599
+ }
53600
+ async listSlackUsers(orgId, query) {
53601
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_USERS(orgId), query));
53602
+ }
53603
+ async slackHistory(orgId, conversationId, query) {
53604
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_HISTORY(orgId), query, { conversation: conversationId }));
53605
+ }
53606
+ /** Read a Slack thread (parent and replies), one page in Slack order. */
53607
+ async slackReplies(orgId, channel, ts, query) {
53608
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_REPLIES(orgId), query, { channel, ts }));
53609
+ }
53610
+ async slackMembers(orgId, conversationId, query) {
53611
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_MEMBERS(orgId), query, { conversation: conversationId }));
53612
+ }
53613
+ /** Set/clear the Agents-pane "typing…" indicator (best-effort cosmetic). */
53614
+ async setSlackStatus(orgId, input) {
53615
+ await this.request("POST", ENDPOINTS.SLACK_STATUS(orgId), input);
53616
+ }
53617
+ };
53618
+
53391
53619
  // ts/sdk/dist/channel-conversation-client.js
53392
- var ChannelConversationClient = class extends SlackFilesClient {
53620
+ var ChannelConversationClient = class extends SlackReadClient {
53393
53621
  /**
53394
53622
  * Org-admin write of what the agent receives from a group root
53395
53623
  * (`PATCH …/channel-conversations/{id}/attention`); the agent's own path
@@ -55063,38 +55291,6 @@ var ParallClient = class _ParallClient extends BrowserProfileClient {
55063
55291
  async sendChannelMessage(orgId, input) {
55064
55292
  return this.request("POST", ENDPOINTS.CHANNEL_SEND(orgId), input);
55065
55293
  }
55066
- slackReadQuery(base, query, extra) {
55067
- const params = new URLSearchParams();
55068
- if (query?.cursor)
55069
- params.set("cursor", query.cursor);
55070
- if (query?.limit)
55071
- params.set("limit", String(query.limit));
55072
- for (const [k, v] of Object.entries(extra ?? {}))
55073
- params.set(k, v);
55074
- const qs = params.toString();
55075
- return qs ? `${base}?${qs}` : base;
55076
- }
55077
- /**
55078
- * Tier-B read verbs (agent-only): workspace visibility as the bot sees
55079
- * it. Same live gate as the send verb; authorization beyond it is the
55080
- * bot's own Slack permissions.
55081
- */
55082
- async listSlackChannels(orgId, query) {
55083
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_CHANNELS(orgId), query));
55084
- }
55085
- async listSlackUsers(orgId, query) {
55086
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_USERS(orgId), query));
55087
- }
55088
- async slackHistory(orgId, conversationId, query) {
55089
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_HISTORY(orgId), query, { conversation: conversationId }));
55090
- }
55091
- async slackMembers(orgId, conversationId, query) {
55092
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_MEMBERS(orgId), query, { conversation: conversationId }));
55093
- }
55094
- /** Set/clear the Agents-pane "typing…" indicator (best-effort cosmetic). */
55095
- async setSlackStatus(orgId, input) {
55096
- await this.request("POST", ENDPOINTS.SLACK_STATUS(orgId), input);
55097
- }
55098
55294
  /**
55099
55295
  * Authorized raw GET (binary responses) with the same auth, 401
55100
55296
  * refresh-and-retry-once, and error-envelope handling as `request` — the
@@ -56809,46 +57005,60 @@ function createActiveForkState(fork, targetId, continuationPrefix) {
56809
57005
  };
56810
57006
  }
56811
57007
 
56812
- // ts/agent-core/dist/redact.js
56813
- function redactSecrets(s, knownValues = []) {
56814
- return maskKnownValues(s, knownValues).replace(/\b(agk|mck|cpk)_[A-Za-z0-9_-]+/g, "$1_***").replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "$1-***").replace(/\bAKIA[0-9A-Z]{16}\b/g, "AKIA***").replace(/\b((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+/gi, "$1***").replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization)["']?\s*[=:]\s*)(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s&;,}\]"']+)/gi, "$1***").replace(/[A-Za-z0-9_-]{32,}/g, "***");
57008
+ // ts/agent-core/dist/gateway-steer.js
57009
+ var pendingSteers = /* @__PURE__ */ new WeakMap();
57010
+ function hasMainSteers(state) {
57011
+ return (pendingSteers.get(state)?.size ?? 0) > 0;
56815
57012
  }
56816
- function maskKnownValues(s, knownValues) {
56817
- let out = s;
56818
- for (const v of knownValues) {
56819
- if (typeof v === "string" && v.length >= 6)
56820
- out = out.split(v).join("***");
56821
- }
56822
- return out;
57013
+ async function waitForMainSteers(state) {
57014
+ await Promise.allSettled(pendingSteers.get(state) ?? []);
56823
57015
  }
56824
- function redactTurnOutcome(event, knownValues) {
56825
- const redacted = { ...event };
56826
- if (redacted.detail)
56827
- redacted.detail = redactSecrets(redacted.detail, knownValues);
56828
- if (redacted.raw) {
56829
- redacted.raw = Object.fromEntries(Object.entries(redacted.raw).map(([k, v]) => [
56830
- k,
56831
- typeof v === "string" ? redactSecrets(v, knownValues) : v
56832
- ]));
57016
+ async function steerLaneMessage(host, event) {
57017
+ let pending = pendingSteers.get(host.dispatchState);
57018
+ if (!pending) {
57019
+ pending = /* @__PURE__ */ new Set();
57020
+ pendingSteers.set(host.dispatchState, pending);
57021
+ }
57022
+ const work = Promise.resolve().then(() => steerLaneMessageInner(host, event));
57023
+ pending.add(work);
57024
+ try {
57025
+ await work;
57026
+ } finally {
57027
+ pending.delete(work);
57028
+ if (pending.size === 0)
57029
+ pendingSteers.delete(host.dispatchState);
57030
+ host.notifyDrainWaiters?.();
56833
57031
  }
56834
- return redacted;
56835
57032
  }
56836
- function describeTurnOutcomeFailure(outcome) {
56837
- const retryNote = outcome.retryAt ? `, retry at ${outcome.retryAt}` : "";
56838
- return {
56839
- warn: `${outcome.outcome}${retryNote}${outcome.detail ? ` \u2014 ${outcome.detail}` : ""}`,
56840
- stepMessage: `LLM turn ${outcome.outcome}${retryNote}${outcome.detail ? `: ${outcome.detail}` : ""}`
56841
- };
57033
+ function hasUninjectedSameLaneEventAhead(host, event) {
57034
+ const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
57035
+ if (eventIndex <= 0)
57036
+ return false;
57037
+ const groupKey = host.dispatchGroupKey(event);
57038
+ return host.dispatchState.mainBuffer.slice(0, eventIndex).some((buffered) => host.dispatchGroupKey(buffered) === groupKey && !host.injectedMainBufferEvents.has(buffered));
56842
57039
  }
56843
- function redactLogger(log2, knownValues) {
56844
- if (!log2)
56845
- return void 0;
56846
- return {
56847
- info: (message) => log2.info(redactSecrets(message, knownValues)),
56848
- warn: (message) => log2.warn(redactSecrets(message, knownValues)),
56849
- error: (message) => log2.error(redactSecrets(message, knownValues)),
56850
- ...log2.child ? { child: (name) => redactLogger(log2.child(name), knownValues) } : {}
56851
- };
57040
+ async function steerLaneMessageInner(host, event) {
57041
+ const { laneLedger: ledger, opts } = host;
57042
+ const adapter = opts.dispatchAdapter;
57043
+ if (!ledger || !adapter.enqueueDuringDispatch)
57044
+ return;
57045
+ if (hasUninjectedSameLaneEventAhead(host, event))
57046
+ return;
57047
+ const folded = await ledger.steerLive(event);
57048
+ if (!folded)
57049
+ return;
57050
+ if (!folded.frame)
57051
+ return;
57052
+ event.frame = folded.frame;
57053
+ const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
57054
+ if (injected) {
57055
+ host.injectedMainBufferEvents.add(event);
57056
+ ledger.markSeen(event, folded.covered);
57057
+ opts.log?.info(`steer frame handed to adapter for ${event.messageId} (will drain for bookkeeping)`);
57058
+ } else if (folded.frame) {
57059
+ ledger.deferFrame(event, folded.frame, folded.covered);
57060
+ opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
57061
+ }
56852
57062
  }
56853
57063
 
56854
57064
  // ts/agent-core/dist/lane-ledger.js
@@ -56898,9 +57108,9 @@ function errorWireClass(cls) {
56898
57108
  }
56899
57109
 
56900
57110
  // ts/agent-core/dist/runtime-instance.js
56901
- import { randomUUID } from "node:crypto";
57111
+ import { randomUUID as randomUUID3 } from "node:crypto";
56902
57112
  function newRuntimeInstanceId() {
56903
- return randomUUID().replace(/-/g, "");
57113
+ return randomUUID3().replace(/-/g, "");
56904
57114
  }
56905
57115
  function isTurnToken(token) {
56906
57116
  return token.startsWith("turn_");
@@ -58598,36 +58808,6 @@ function applyWake(event, wake) {
58598
58808
  if (wake.attachments?.length)
58599
58809
  event.attachments = wake.attachments;
58600
58810
  }
58601
- function hasUninjectedSameLaneEventAhead(host, event) {
58602
- const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
58603
- if (eventIndex <= 0)
58604
- return false;
58605
- const groupKey = host.dispatchGroupKey(event);
58606
- return host.dispatchState.mainBuffer.slice(0, eventIndex).some((buffered) => host.dispatchGroupKey(buffered) === groupKey && !host.injectedMainBufferEvents.has(buffered));
58607
- }
58608
- async function steerLaneMessage(host, event) {
58609
- const { laneLedger: ledger, opts } = host;
58610
- const adapter = opts.dispatchAdapter;
58611
- if (!ledger || !adapter.enqueueDuringDispatch)
58612
- return;
58613
- if (hasUninjectedSameLaneEventAhead(host, event))
58614
- return;
58615
- const folded = await ledger.steerLive(event);
58616
- if (!folded)
58617
- return;
58618
- if (!folded.frame)
58619
- return;
58620
- event.frame = folded.frame;
58621
- const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
58622
- if (injected) {
58623
- host.injectedMainBufferEvents.add(event);
58624
- ledger.markSeen(event, folded.covered);
58625
- opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
58626
- } else if (folded.frame) {
58627
- ledger.deferFrame(event, folded.frame, folded.covered);
58628
- opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
58629
- }
58630
- }
58631
58811
  async function dispatchLaneGroup(host, opts) {
58632
58812
  const event = opts.events[opts.events.length - 1];
58633
58813
  return runInDispatchTrace({
@@ -58733,6 +58913,9 @@ async function dispatchLaneGroupInner(host, opts) {
58733
58913
  ]);
58734
58914
  dispatched = await host.runDispatch(event, opts.sessionKey, opts.bodyPrefix + eventBody(event), opts.earlier, opts.captureText, inputLifecycle);
58735
58915
  } catch (err) {
58916
+ while (opts.sessionKey === host.opts.runtimeKey && hasMainSteers(host.dispatchState)) {
58917
+ await waitForMainSteers(host.dispatchState);
58918
+ }
58736
58919
  host.noteSessionLane(opts.sessionKey, null);
58737
58920
  await runInPhaseSpan("settle", () => ledger.release(lane.laneKey, "runtime_error", releaseErrorInfo(err, [host.opts.config.api_key])).catch(() => {
58738
58921
  }));
@@ -58744,6 +58927,9 @@ async function dispatchLaneGroupInner(host, opts) {
58744
58927
  if (!dispatched) {
58745
58928
  return "shutdown";
58746
58929
  }
58930
+ while (opts.sessionKey === host.opts.runtimeKey && hasMainSteers(host.dispatchState)) {
58931
+ await waitForMainSteers(host.dispatchState);
58932
+ }
58747
58933
  const settled = host.consumeTurnOutcome(opts.sessionKey);
58748
58934
  if (settled) {
58749
58935
  if (settled.kind === "deferred") {
@@ -59087,6 +59273,19 @@ async function handleCompactSignal(host, data) {
59087
59273
  // ts/agent-core/dist/gateway-runtime-turns.js
59088
59274
  var UNTARGETED_STEP = { target_type: "" };
59089
59275
  function handleRuntimeActivity(host, event) {
59276
+ if (event.kind === "observation") {
59277
+ const binding = host.sessionBindings.get(event.sessionKey);
59278
+ if (!binding || binding.runtimeSessionId !== event.event.runtimeSessionId) {
59279
+ host.opts.log?.warn(`runtime observation has no matching session binding on ${event.sessionKey}`);
59280
+ return;
59281
+ }
59282
+ host.inFlightRuntimeTurns += 1;
59283
+ void persistRuntimeObservation(host.stepPersister, binding.agentSessionId, UNTARGETED_STEP, event.event, host.opts.log, [host.opts.config.api_key]).finally(() => {
59284
+ host.inFlightRuntimeTurns -= 1;
59285
+ host.notifyDrainWaiters();
59286
+ });
59287
+ return;
59288
+ }
59090
59289
  const sessionKey = event.kind === "turn" ? event.turn.sessionKey : event.sessionKey;
59091
59290
  const label = event.kind === "turn" ? `runtime-initiated turn ${event.turn.groupKey} on ${sessionKey}` : `runtime child session close for ${sessionKey}`;
59092
59291
  const prior = host.runtimeActivityChains.get(sessionKey) ?? Promise.resolve();
@@ -59129,7 +59328,8 @@ async function runRuntimeTurn(host, turn) {
59129
59328
  };
59130
59329
  try {
59131
59330
  for await (const runtimeEvent of turn.events) {
59132
- deadline.touch();
59331
+ if (runtimeEvent.type !== "observation")
59332
+ deadline.touch();
59133
59333
  if (runtimeEvent.type === "runtime_session") {
59134
59334
  try {
59135
59335
  binding = await host.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath);
@@ -59139,7 +59339,7 @@ async function runRuntimeTurn(host, turn) {
59139
59339
  }
59140
59340
  continue;
59141
59341
  }
59142
- if (!binding) {
59342
+ if (!binding || runtimeEvent.type === "observation" && binding.runtimeSessionId !== runtimeEvent.runtimeSessionId) {
59143
59343
  droppedWithoutBinding += 1;
59144
59344
  continue;
59145
59345
  }
@@ -59154,7 +59354,8 @@ async function runRuntimeTurn(host, turn) {
59154
59354
  await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, { type: "error", message: failure.stepMessage, groupKey }, void 0, contextFilePath);
59155
59355
  continue;
59156
59356
  }
59157
- await ensureBegun();
59357
+ if (runtimeEvent.type !== "observation")
59358
+ await ensureBegun();
59158
59359
  stepCount += 1;
59159
59360
  await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, runtimeEvent, void 0, contextFilePath);
59160
59361
  }
@@ -60310,11 +60511,11 @@ function parseDispatchDeadlineMs(raw) {
60310
60511
  }
60311
60512
  function inputStepIdempotencyKey(event) {
60312
60513
  if (event.type === "message" || event.type === "channel_message") {
60313
- return event.messageId ? `input:${event.messageId}` : randomUUID2();
60514
+ return event.messageId ? `input:${event.messageId}` : randomUUID4();
60314
60515
  }
60315
60516
  if (event.dispatchEventId)
60316
60517
  return `input:${event.dispatchEventId}`;
60317
- return randomUUID2();
60518
+ return randomUUID4();
60318
60519
  }
60319
60520
  function resolveStepTarget(event) {
60320
60521
  if (event.input?.step_target) {
@@ -60821,100 +61022,7 @@ var ParallAgentGateway = class {
60821
61022
  });
60822
61023
  }
60823
61024
  async createRuntimeStep(sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2) {
60824
- switch (runtimeEvent.type) {
60825
- case "thinking":
60826
- await this.stepPersister.persist(sessionId, "thinking", {
60827
- step_type: "thinking",
60828
- target_type: target.target_type,
60829
- target_id: target.target_id,
60830
- idempotency_key: randomUUID2(),
60831
- content: { text: runtimeEvent.text },
60832
- group_key: runtimeEvent.groupKey
60833
- });
60834
- break;
60835
- case "text":
60836
- await this.stepPersister.persist(sessionId, "text", {
60837
- step_type: "text",
60838
- target_type: target.target_type,
60839
- target_id: target.target_id,
60840
- idempotency_key: randomUUID2(),
60841
- content: {
60842
- text: runtimeEvent.text,
60843
- suppressed: runtimeEvent.project !== true
60844
- },
60845
- projection: runtimeEvent.project === true,
60846
- group_key: runtimeEvent.groupKey
60847
- });
60848
- break;
60849
- case "tool_call": {
60850
- const step = await this.stepPersister.persist(sessionId, "tool_call", {
60851
- step_type: "tool_call",
60852
- target_type: target.target_type,
60853
- target_id: target.target_id,
60854
- // call_id is session-unique for bridge runtimes (server-enforced),
60855
- // so the bare form anchors the tool step pair across retries —
60856
- // unlike parel's turn-scoped `tc:{turnId}:{callId}` (see
60857
- // protocol-vectors/agent-steps.json).
60858
- idempotency_key: `tc:${runtimeEvent.callId}`,
60859
- content: {
60860
- call_id: runtimeEvent.callId,
60861
- tool_name: runtimeEvent.toolName,
60862
- tool_input: runtimeEvent.input,
60863
- status: "running",
60864
- started_at: runtimeEvent.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
60865
- },
60866
- group_key: runtimeEvent.groupKey,
60867
- runtime_key: runtimeEvent.callId
60868
- });
60869
- if (step) {
60870
- if (contextFilePath) {
60871
- this.updateContextFileStepId(contextFilePath, step.id);
60872
- } else if (stepIdFilePath) {
60873
- this.writeStepIdFile(stepIdFilePath, step.id);
60874
- }
60875
- if (laneContextFilePath2) {
60876
- this.updateContextFileStepId(laneContextFilePath2, step.id);
60877
- }
60878
- }
60879
- break;
60880
- }
60881
- case "tool_result":
60882
- await this.stepPersister.persist(sessionId, "tool_result", {
60883
- step_type: "tool_result",
60884
- target_type: target.target_type,
60885
- target_id: target.target_id,
60886
- idempotency_key: `tr:${runtimeEvent.callId}`,
60887
- content: {
60888
- call_id: runtimeEvent.callId,
60889
- tool_name: runtimeEvent.toolName,
60890
- status: runtimeEvent.error ? "error" : "success",
60891
- output: runtimeEvent.output,
60892
- duration_ms: runtimeEvent.durationMs ?? 0,
60893
- collapsible: true
60894
- },
60895
- group_key: runtimeEvent.groupKey
60896
- });
60897
- if (contextFilePath) {
60898
- this.updateContextFileStepId(contextFilePath, null);
60899
- } else if (stepIdFilePath) {
60900
- this.clearStepIdFile(stepIdFilePath);
60901
- }
60902
- if (laneContextFilePath2) {
60903
- this.updateContextFileStepId(laneContextFilePath2, null);
60904
- }
60905
- break;
60906
- case "error":
60907
- await this.stepPersister.persist(sessionId, "error", {
60908
- step_type: "text",
60909
- target_type: target.target_type,
60910
- target_id: target.target_id,
60911
- idempotency_key: randomUUID2(),
60912
- content: buildErrorStepContent(runtimeEvent.message),
60913
- projection: false,
60914
- group_key: runtimeEvent.groupKey
60915
- });
60916
- break;
60917
- }
61025
+ return createRuntimeStep(this, sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
60918
61026
  }
60919
61027
  writeContextFile(filePath, ctx) {
60920
61028
  try {
@@ -61064,7 +61172,8 @@ var ParallAgentGateway = class {
61064
61172
  inputLifecycle,
61065
61173
  noteActivity: dispatchDeadline.touch
61066
61174
  })) {
61067
- dispatchDeadline.touch();
61175
+ if (runtimeEvent.type !== "observation")
61176
+ dispatchDeadline.touch();
61068
61177
  if (runtimeEvent.type === "runtime_session") {
61069
61178
  const priorAgentSessionId = binding?.agentSessionId;
61070
61179
  binding = await runInPhaseSpan("session", () => this.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2));
@@ -61089,6 +61198,14 @@ var ParallAgentGateway = class {
61089
61198
  }
61090
61199
  continue;
61091
61200
  }
61201
+ if (runtimeEvent.type === "observation") {
61202
+ if (binding?.runtimeSessionId === runtimeEvent.runtimeSessionId) {
61203
+ await this.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent);
61204
+ } else {
61205
+ this.opts.log?.warn("runtime observation has no matching active session binding");
61206
+ }
61207
+ continue;
61208
+ }
61092
61209
  if (runtimeEvent.type === "turn_outcome") {
61093
61210
  const outcomeEvent = redactTurnOutcome(runtimeEvent, [this.opts.config.api_key]);
61094
61211
  turnOutcomeEvent = outcomeEvent;
@@ -61461,6 +61578,8 @@ var ParallAgentGateway = class {
61461
61578
  while (this.idleCompact.inFlight)
61462
61579
  await this.idleCompact.inFlight;
61463
61580
  while (this.dispatchState.mainBuffer.length > 0) {
61581
+ while (hasMainSteers(this.dispatchState))
61582
+ await waitForMainSteers(this.dispatchState);
61464
61583
  if (this.shuttingDown) {
61465
61584
  this.opts.log?.info(`drainMainBuffer halted (shutting down) \u2014 ${this.dispatchState.mainBuffer.length} buffered, ${this.dispatchState.pendingForkResults.length} pending fork results left for catch-up`);
61466
61585
  break;
@@ -62036,13 +62155,9 @@ ${fullSummary}` : fullSummary;
62036
62155
  }
62037
62156
  }
62038
62157
  }
62039
- /**
62040
- * Nothing in flight: no dispatch, no runtime-initiated turn, and the
62041
- * runtime itself reports idle (isBusy — a turn it is executing that has
62042
- * not surfaced yet, or a follow-up hold after background work finished).
62043
- */
62158
+ /** Drain includes in-flight native work and unfinished steer registration. */
62044
62159
  isDrained() {
62045
- return this.inFlightDispatches === 0 && this.inFlightRuntimeTurns === 0 && !this.adapterBusy();
62160
+ return this.inFlightDispatches === 0 && this.inFlightRuntimeTurns === 0 && !hasMainSteers(this.dispatchState) && !this.adapterBusy();
62046
62161
  }
62047
62162
  adapterBusy() {
62048
62163
  try {
@@ -63927,12 +64042,12 @@ var RuntimeActivityPort = class {
63927
64042
  };
63928
64043
 
63929
64044
  // ts/agent-core/dist/runtime-turn-base.js
63930
- import { randomUUID as randomUUID3 } from "node:crypto";
64045
+ import { randomUUID as randomUUID5 } from "node:crypto";
63931
64046
  var RuntimeTurnBase = class {
63932
64047
  sessionKey;
63933
64048
  trigger;
63934
64049
  onDetach;
63935
- groupKey = randomUUID3();
64050
+ groupKey = randomUUID5();
63936
64051
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
63937
64052
  activityListeners = [];
63938
64053
  detached = false;
@@ -64039,7 +64154,7 @@ function stepIdFilePathForSession(stateDir, sessionKey) {
64039
64154
 
64040
64155
  // ts/claude-agent/dist/dispatch.js
64041
64156
  import { execSync as execSync2, spawn } from "node:child_process";
64042
- import { randomUUID as randomUUID6 } from "node:crypto";
64157
+ import { randomUUID as randomUUID8 } from "node:crypto";
64043
64158
  import * as fs8 from "node:fs";
64044
64159
  import * as path11 from "node:path";
64045
64160
 
@@ -64616,7 +64731,7 @@ function parseContentLength(value) {
64616
64731
  }
64617
64732
 
64618
64733
  // ts/claude-agent/dist/compact.js
64619
- import { randomUUID as randomUUID4 } from "node:crypto";
64734
+ import { randomUUID as randomUUID6 } from "node:crypto";
64620
64735
  async function runClaudeCompact(host, { sessionKey, signal, log: log2 }) {
64621
64736
  if (signal.aborted)
64622
64737
  return { status: "timeout" };
@@ -64630,7 +64745,7 @@ async function runClaudeCompact(host, { sessionKey, signal, log: log2 }) {
64630
64745
  if (state.inputs.hasPendingInjections() || state.inputs.hasUnsettledInjections()) {
64631
64746
  return { status: "failed", detail: "injections still pending on the session" };
64632
64747
  }
64633
- const delivery = state.inputs.register(`compact:${randomUUID4()}`, void 0, false);
64748
+ const delivery = state.inputs.register(`compact:${randomUUID6()}`, void 0, false);
64634
64749
  try {
64635
64750
  host.writeUserMessage(state.handle, "/compact", delivery.commandUuid);
64636
64751
  } catch (err) {
@@ -64814,7 +64929,7 @@ function aggregateBusyState(states) {
64814
64929
  }
64815
64930
 
64816
64931
  // ts/claude-agent/dist/input-lifecycle.js
64817
- import { randomUUID as randomUUID5 } from "node:crypto";
64932
+ import { randomUUID as randomUUID7 } from "node:crypto";
64818
64933
 
64819
64934
  // ts/claude-agent/dist/turn-outcome.js
64820
64935
  var LIMIT_TEXT = /you'?ve (hit|reached) your .*limit|usage limit reached|weekly limit/i;
@@ -65056,7 +65171,7 @@ var ClaudeInputRegistry = class {
65056
65171
  if (this.byKey.has(deliveryKey)) {
65057
65172
  throw new Error(`duplicate Claude delivery key ${deliveryKey}`);
65058
65173
  }
65059
- const commandUuid = randomUUID5();
65174
+ const commandUuid = randomUUID7();
65060
65175
  const delivery = {
65061
65176
  deliveryKey,
65062
65177
  commandUuid,
@@ -65157,6 +65272,60 @@ var ClaudeInputRegistry = class {
65157
65272
  }
65158
65273
  };
65159
65274
 
65275
+ // ts/claude-agent/dist/runtime-observations.js
65276
+ function claudeObservation(frame) {
65277
+ const sessionId = observationField(frame.session_id);
65278
+ if (!sessionId || frame.parent_tool_use_id)
65279
+ return;
65280
+ const native = {
65281
+ session_id: sessionId,
65282
+ event_id: observationField(frame.uuid)
65283
+ };
65284
+ let event;
65285
+ let status = "unknown";
65286
+ if (frame.type === "result") {
65287
+ event = "request_completed";
65288
+ status = frame.is_error === true ? "failed" : frame.is_error === false ? "completed" : "unknown";
65289
+ native.status = observationField(frame.subtype);
65290
+ if (typeof frame.num_turns === "number" && Number.isSafeInteger(frame.num_turns) && frame.num_turns >= 0) {
65291
+ native.num_turns = frame.num_turns;
65292
+ }
65293
+ } else if (frame.type === "system") {
65294
+ switch (frame.subtype) {
65295
+ case "init":
65296
+ event = "session_initialized";
65297
+ status = "initialized";
65298
+ break;
65299
+ case "hook_started":
65300
+ case "hook_response":
65301
+ event = frame.subtype === "hook_started" ? "hook_started" : "hook_completed";
65302
+ status = frame.subtype === "hook_started" ? "running" : frame.outcome === "success" ? "completed" : frame.outcome === "error" ? "failed" : frame.outcome === "cancelled" ? "stopped" : "unknown";
65303
+ native.hook_id = observationField(frame.hook_id);
65304
+ native.hook_event = observationField(frame.hook_event);
65305
+ native.status = observationField(frame.outcome);
65306
+ break;
65307
+ case "status":
65308
+ case "session_state_changed":
65309
+ event = "session_status";
65310
+ native.status = observationField(frame.status) ?? observationField(frame.state);
65311
+ if (native.status === "compacting" || native.status === "running" || native.status === "idle") {
65312
+ status = native.status;
65313
+ }
65314
+ break;
65315
+ default:
65316
+ return;
65317
+ }
65318
+ } else
65319
+ return;
65320
+ return runtimeObservation(sessionId, {
65321
+ runtime: "claude-code",
65322
+ source: "stream_json",
65323
+ event,
65324
+ status,
65325
+ native
65326
+ });
65327
+ }
65328
+
65160
65329
  // ts/claude-agent/dist/output-parser.js
65161
65330
  var RUNTIME_TASK_SUBTYPES = /* @__PURE__ */ new Set([
65162
65331
  "background_tasks_changed",
@@ -65257,6 +65426,9 @@ async function* parseClaudeStreamJson(readable) {
65257
65426
  const now = Date.now();
65258
65427
  const eventTimestampMs = parseEventTimestampMs(event) ?? now;
65259
65428
  const eventRecord = event;
65429
+ const observation = claudeObservation(eventRecord);
65430
+ if (observation && observation.content.event !== "session_initialized")
65431
+ yield observation;
65260
65432
  if (eventRecord.type === "system" && eventRecord.subtype === "compact_boundary") {
65261
65433
  const meta = eventRecord.compact_metadata && typeof eventRecord.compact_metadata === "object" ? eventRecord.compact_metadata : void 0;
65262
65434
  const trigger = asTrimmedString(meta?.trigger);
@@ -65277,6 +65449,8 @@ async function* parseClaudeStreamJson(readable) {
65277
65449
  ...sessionId ? { sessionId } : {},
65278
65450
  capabilities
65279
65451
  };
65452
+ if (observation)
65453
+ yield observation;
65280
65454
  continue;
65281
65455
  }
65282
65456
  const subtype = asTrimmedString(eventRecord.subtype);
@@ -65569,6 +65743,7 @@ var ClaudeProcessPump = class {
65569
65743
  idleTimer = null;
65570
65744
  activeDrain = null;
65571
65745
  now;
65746
+ pendingObservations = [];
65572
65747
  constructor(opts) {
65573
65748
  this.opts = opts;
65574
65749
  this.now = opts.now ?? Date.now;
@@ -65689,7 +65864,8 @@ var ClaudeProcessPump = class {
65689
65864
  for await (const parsed of parser) {
65690
65865
  if (this.closed)
65691
65866
  break;
65692
- this.touchAll();
65867
+ if (parsed.type !== "observation")
65868
+ this.touchAll();
65693
65869
  await this.route(parsed);
65694
65870
  }
65695
65871
  } catch (err) {
@@ -65702,6 +65878,9 @@ var ClaudeProcessPump = class {
65702
65878
  switch (parsed.type) {
65703
65879
  case "runtime_activity":
65704
65880
  return;
65881
+ case "observation":
65882
+ this.routeObservation(parsed);
65883
+ return;
65705
65884
  case "runtime_init":
65706
65885
  this.handleInit(parsed);
65707
65886
  return;
@@ -65751,6 +65930,24 @@ var ClaudeProcessPump = class {
65751
65930
  }
65752
65931
  this.runtimeTurn?.touch();
65753
65932
  }
65933
+ routeObservation(event) {
65934
+ if (!this.sessionId) {
65935
+ if (this.pendingObservations.length < 64)
65936
+ this.pendingObservations.push(event);
65937
+ else
65938
+ this.opts.log?.warn("Claude startup observation buffer full; dropping observation");
65939
+ return;
65940
+ }
65941
+ if (event.runtimeSessionId !== this.sessionId) {
65942
+ this.opts.log?.warn("Claude observation does not match the initialized session");
65943
+ return;
65944
+ }
65945
+ const owner = this.ownerFor(false) ?? (this.activeDrain && !this.activeDrain.terminal ? this.activeDrain : null);
65946
+ if (owner)
65947
+ owner.sink.push({ kind: "runtime", event });
65948
+ else
65949
+ this.opts.hooks.onObservation?.(event);
65950
+ }
65754
65951
  liveDeliveries() {
65755
65952
  const live = [];
65756
65953
  for (const delivery of this.opts.inputs.values())
@@ -65820,6 +66017,10 @@ var ClaudeProcessPump = class {
65820
66017
  delivery.sessionAnnounced = true;
65821
66018
  delivery.sink.push({ kind: "runtime", event: announce });
65822
66019
  }
66020
+ const pending = this.pendingObservations;
66021
+ this.pendingObservations = [];
66022
+ for (const event of pending)
66023
+ this.routeObservation(event);
65823
66024
  }
65824
66025
  async handleLifecycle(parsed) {
65825
66026
  if (!this.capabilities.has("msg_lifecycle_v1")) {
@@ -65960,6 +66161,9 @@ function buildSpawnEnv(parentEnv, claudeHome, context2, opts) {
65960
66161
  const result = {
65961
66162
  ...env,
65962
66163
  HOME: claudeHome,
66164
+ // Request native state frames for observation without changing user files.
66165
+ // Preserve an operator's explicit opt-out; older CLIs can ignore the flag.
66166
+ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: env.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS ?? "1",
65963
66167
  PRLL_API_URL: context2.apiUrl,
65964
66168
  PRLL_API_KEY: context2.apiKey,
65965
66169
  PRLL_ORG_ID: context2.orgId,
@@ -66371,7 +66575,7 @@ var ClaudeCodeAdapter = class {
66371
66575
  async *consumeDelivery(sessionKey, state, target, noteActivity) {
66372
66576
  if (target.terminal)
66373
66577
  return;
66374
- const groupKey = randomUUID6();
66578
+ const groupKey = randomUUID8();
66375
66579
  state.pump.setActiveDrain(target, noteActivity);
66376
66580
  try {
66377
66581
  while (true) {
@@ -66480,10 +66684,9 @@ var ClaudeCodeAdapter = class {
66480
66684
  this.processes.delete(sessionKey);
66481
66685
  this.retiring.delete(state);
66482
66686
  },
66483
- // Main-session turns go to the gateway (steps + session activity);
66484
- // fork-session turns only count as busy (fork-scope invariant).
66485
66687
  onRuntimeTurnOpened: (turn) => this.activity.surfaceTurn(turn, this.opts.sessionManager.isMain(sessionKey), log2),
66486
- onRuntimeTurnClosed: () => this.maybeApplyRestart(sessionKey, state)
66688
+ onRuntimeTurnClosed: () => this.maybeApplyRestart(sessionKey, state),
66689
+ onObservation: (event) => this.activity.emit({ kind: "observation", sessionKey, event }, log2)
66487
66690
  }
66488
66691
  }),
66489
66692
  done: false,
@@ -66572,7 +66775,7 @@ var ClaudeCodeAdapter = class {
66572
66775
  writeCapabilityProbe(handle) {
66573
66776
  const payload = JSON.stringify({
66574
66777
  type: "user",
66575
- uuid: randomUUID6(),
66778
+ uuid: randomUUID8(),
66576
66779
  parent_tool_use_id: null,
66577
66780
  message: { role: "user", content: [] }
66578
66781
  });
@@ -66646,7 +66849,7 @@ var ClaudeCodeAdapter = class {
66646
66849
  // ts/claude-agent/dist/session-manager.js
66647
66850
  import * as fs9 from "node:fs";
66648
66851
  import * as path12 from "node:path";
66649
- import { randomUUID as randomUUID7 } from "node:crypto";
66852
+ import { randomUUID as randomUUID9 } from "node:crypto";
66650
66853
  var ClaudeSessionManager = class _ClaudeSessionManager {
66651
66854
  mainSessionKey;
66652
66855
  stateFilePath;
@@ -66686,7 +66889,7 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
66686
66889
  const parentSessionId = this.sessionIds.get(parentSessionKey);
66687
66890
  if (!parentSessionId)
66688
66891
  return null;
66689
- const sessionKey = `claude-fork:${randomUUID7()}`;
66892
+ const sessionKey = `claude-fork:${randomUUID9()}`;
66690
66893
  this.pendingForkParents.set(sessionKey, parentSessionId);
66691
66894
  return {
66692
66895
  sessionKey,