@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,7 +59273,20 @@ 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) {
59090
- const sessionKey = event.kind === "turn" ? event.turn.sessionKey : event.sessionKey;
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
+ }
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();
59093
59292
  host.inFlightRuntimeTurns += 1;
@@ -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 {
@@ -63914,12 +64029,12 @@ var RuntimeActivityPort = class {
63914
64029
  };
63915
64030
 
63916
64031
  // ts/agent-core/dist/runtime-turn-base.js
63917
- import { randomUUID as randomUUID3 } from "node:crypto";
64032
+ import { randomUUID as randomUUID5 } from "node:crypto";
63918
64033
  var RuntimeTurnBase = class {
63919
64034
  sessionKey;
63920
64035
  trigger;
63921
64036
  onDetach;
63922
- groupKey = randomUUID3();
64037
+ groupKey = randomUUID5();
63923
64038
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
63924
64039
  activityListeners = [];
63925
64040
  detached = false;
@@ -64040,872 +64155,902 @@ function stepIdFilePathForSession(stateDir, sessionKey) {
64040
64155
  return path8.join(stateDir, "step-ids", `${fileName}.txt`);
64041
64156
  }
64042
64157
 
64043
- // ts/codex-agent/dist/dispatch.js
64044
- import { spawn } from "node:child_process";
64045
- import { randomUUID as randomUUID4 } from "node:crypto";
64046
- import * as path11 from "node:path";
64047
-
64048
- // ts/agent-core/dist/internal/attachment-input.js
64049
- import { execSync } from "node:child_process";
64050
- import { constants } from "node:fs";
64051
- import * as fsSync from "node:fs";
64052
- import * as fs7 from "node:fs/promises";
64053
- import * as path9 from "node:path";
64054
- var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
64055
- var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
64056
- var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
64057
- var DEFAULT_ATTACHMENT_TTL_MS = 24 * 60 * 60 * 1e3;
64058
- var DEFAULT_MAINTENANCE_COOLDOWN_MS = 60 * 1e3;
64059
- var SUPPORTED_IMAGE_MIME_TYPES = /* @__PURE__ */ new Set([
64060
- "image/png",
64061
- "image/jpeg",
64062
- "image/jpg",
64063
- "image/webp",
64064
- "image/gif"
64065
- ]);
64066
- var activeAttachmentDirs = /* @__PURE__ */ new Set();
64067
- async function prepareLocalImageAttachments(event, context2, opts) {
64068
- const attachments = event.attachments ?? [];
64069
- const imageAttachments = attachments.filter((att) => SUPPORTED_IMAGE_MIME_TYPES.has(att.mimeType.toLowerCase()));
64070
- if (imageAttachments.length === 0)
64071
- return { images: [], notes: [] };
64072
- const maxTotalImageBytes = opts.maxTotalImageBytes ?? DEFAULT_MAX_TOTAL_IMAGE_BYTES;
64073
- const totalDeclaredBytes = imageAttachments.reduce((sum, att) => sum + Math.max(0, att.fileSize), 0);
64074
- if (totalDeclaredBytes > maxTotalImageBytes) {
64075
- return {
64076
- images: [],
64077
- notes: [
64078
- `[Image attachments not downloaded: total size ${formatBytes(totalDeclaredBytes)} exceeds bridge limit ${formatBytes(maxTotalImageBytes)}]`
64079
- ]
64080
- };
64081
- }
64082
- const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
64083
- const messageDir = path9.join(rootDir, sanitizePathSegment(event.messageId));
64084
- await ensurePathIsNotSymlink(messageDir);
64085
- await fs7.mkdir(messageDir, { recursive: true });
64086
- await ensurePathIsNotSymlink(messageDir);
64087
- const activeMessageDir = path9.resolve(messageDir);
64088
- activeAttachmentDirs.add(activeMessageDir);
64089
- const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
64090
- const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
64091
- ttlMs: opts.attachmentTtlMs ?? DEFAULT_ATTACHMENT_TTL_MS,
64092
- maxBytes: opts.maxCacheBytes ?? DEFAULT_ATTACHMENT_CACHE_MAX_BYTES,
64093
- cooldownMs: maintenanceCooldownMs,
64094
- log: opts.log
64095
- });
64096
- if (maintenanceCooldownMs === 0 && maintenancePromise) {
64097
- await maintenancePromise;
64098
- }
64099
- try {
64100
- const images = [];
64101
- const notes = [];
64102
- let downloadedBytes = 0;
64103
- for (const att of imageAttachments) {
64104
- const localPath = path9.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
64105
- const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
64106
- const fetchFresh = async () => {
64107
- const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
64108
- downloadedBytes += await downloadAttachmentToFile(fileInfo.url, localPath, maxTotalImageBytes - downloadedBytes, downloadTimeoutMs, rootDir);
64109
- };
64110
- const cameFromCache = await existingUsableFile(localPath, att.fileSize, rootDir);
64111
- if (!cameFromCache) {
64112
- try {
64113
- await fetchFresh();
64114
- } catch (err) {
64115
- opts.log?.warn?.(`agent-core: failed to prepare local image attachment ${att.id}: ${String(err)}`);
64116
- notes.push(`[Image attachment unavailable locally: prll://${sanitizeMeta2(att.id)}]`);
64117
- continue;
64118
- }
64119
- }
64120
- let mimeOk = await downloadedFileMatchesImageMime(localPath, att.mimeType, rootDir);
64121
- if (!mimeOk && cameFromCache) {
64122
- await removeLocalFileIfInside(localPath, rootDir);
64123
- try {
64124
- await fetchFresh();
64125
- } catch (err) {
64126
- opts.log?.warn?.(`agent-core: failed to re-download corrupted cache for ${att.id}: ${String(err)}`);
64127
- notes.push(`[Image attachment unavailable locally: prll://${sanitizeMeta2(att.id)}]`);
64128
- continue;
64129
- }
64130
- mimeOk = await downloadedFileMatchesImageMime(localPath, att.mimeType, rootDir);
64131
- }
64132
- if (!mimeOk) {
64133
- await removeLocalFileIfInside(localPath, rootDir);
64134
- notes.push(`[Image attachment unavailable locally: prll://${sanitizeMeta2(att.id)} (downloaded content does not match ${sanitizeMeta2(att.mimeType)})]`);
64135
- continue;
64136
- }
64137
- images.push({
64138
- attachmentId: att.id,
64139
- fileName: att.fileName,
64140
- mimeType: att.mimeType,
64141
- fileSize: att.fileSize,
64142
- localPath
64143
- });
64144
- }
64145
- return { images, notes };
64146
- } finally {
64147
- activeAttachmentDirs.delete(activeMessageDir);
64148
- }
64158
+ // ts/codex-agent/dist/app-server-protocol.js
64159
+ function buildTurnInput(body, images) {
64160
+ return [
64161
+ { type: "text", text: body },
64162
+ ...images.map((image) => ({ type: "localImage", path: image.localPath }))
64163
+ ];
64149
64164
  }
64150
- function appendLocalAttachmentRefs(body, result) {
64151
- const section = renderLocalAttachmentSection(result);
64152
- return section ? `${body}
64153
-
64154
- ${section}` : body;
64165
+ function extractThreadId(result) {
64166
+ if (!result || typeof result !== "object")
64167
+ return void 0;
64168
+ const r = result;
64169
+ if (typeof r.threadId === "string")
64170
+ return r.threadId;
64171
+ const thread = r.thread;
64172
+ if (thread && typeof thread.id === "string")
64173
+ return thread.id;
64174
+ return void 0;
64155
64175
  }
64156
- async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
64157
- const attachments = await prepareLocalImageAttachments(event, context2, opts);
64158
- return { body: appendLocalAttachmentRefs(body, attachments), attachments };
64176
+ function extractTurnId(result) {
64177
+ if (!result || typeof result !== "object")
64178
+ return void 0;
64179
+ const r = result;
64180
+ if (typeof r.turnId === "string")
64181
+ return r.turnId;
64182
+ const turn = r.turn;
64183
+ if (turn && typeof turn.id === "string")
64184
+ return turn.id;
64185
+ return void 0;
64159
64186
  }
64160
- function pinLocalAttachmentPaths(images) {
64161
- const dirs = new Set(images.map((image) => path9.resolve(path9.dirname(image.localPath))));
64162
- for (const dir of dirs) {
64163
- activeAttachmentDirs.add(dir);
64164
- }
64165
- let released = false;
64166
- return () => {
64167
- if (released)
64168
- return;
64169
- released = true;
64170
- for (const dir of dirs) {
64171
- activeAttachmentDirs.delete(dir);
64172
- }
64187
+ function extractThreadInfo(params) {
64188
+ if (!params || typeof params !== "object")
64189
+ return void 0;
64190
+ const p = params;
64191
+ const thread = p.thread && typeof p.thread === "object" ? p.thread : p;
64192
+ const id = typeof thread.id === "string" ? thread.id : typeof p.threadId === "string" ? p.threadId : void 0;
64193
+ if (!id)
64194
+ return void 0;
64195
+ const str = (value) => typeof value === "string" && value.trim() ? value : void 0;
64196
+ return {
64197
+ id,
64198
+ parentThreadId: str(thread.parentThreadId),
64199
+ source: str(thread.threadSource) ?? str(thread.source),
64200
+ nickname: str(thread.agentNickname),
64201
+ role: str(thread.agentRole)
64173
64202
  };
64174
64203
  }
64175
- function attachmentRootDir(workspaceDir) {
64176
- return path9.join(path9.resolve(workspaceDir), ".parall", "attachments");
64204
+ function extractThreadIdFromNotification(params) {
64205
+ if (!params || typeof params !== "object")
64206
+ return void 0;
64207
+ const p = params;
64208
+ if (typeof p.threadId === "string")
64209
+ return p.threadId;
64210
+ const thread = p.thread;
64211
+ if (thread && typeof thread.id === "string")
64212
+ return thread.id;
64213
+ const meta = p._meta ?? p.meta;
64214
+ if (meta && typeof meta.threadId === "string")
64215
+ return meta.threadId;
64216
+ return void 0;
64177
64217
  }
64178
- function ensureLocalAttachmentGitExclude(workingDirectory) {
64179
- try {
64180
- const rel = execSync("git rev-parse --git-path info/exclude", {
64181
- cwd: workingDirectory,
64182
- encoding: "utf8",
64183
- stdio: ["ignore", "pipe", "ignore"]
64184
- }).trim();
64185
- const excludePath = path9.isAbsolute(rel) ? rel : path9.join(workingDirectory, rel);
64186
- fsSync.mkdirSync(path9.dirname(excludePath), { recursive: true });
64187
- const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
64188
- if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
64189
- return;
64190
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
64191
- fsSync.appendFileSync(excludePath, `${prefix}.parall/
64192
- `, "utf8");
64193
- } catch {
64218
+
64219
+ // ts/codex-agent/dist/jsonrpc-client.js
64220
+ var JSON_RPC_METHOD_NOT_FOUND = -32601;
64221
+ var JsonRpcError = class extends Error {
64222
+ code;
64223
+ data;
64224
+ constructor(code, message, data) {
64225
+ super(message || "JSON-RPC error");
64226
+ this.code = code;
64227
+ this.data = data;
64228
+ this.name = "JsonRpcError";
64194
64229
  }
64195
- }
64196
- var maintenanceStateByRoot = /* @__PURE__ */ new Map();
64197
- function scheduleAttachmentMaintenance(rootDir, opts) {
64198
- const state = maintenanceStateByRoot.get(rootDir);
64199
- if (state?.inFlight)
64200
- return state.inFlight;
64201
- const now = Date.now();
64202
- if (state && now - state.lastRunMs < opts.cooldownMs)
64203
- return null;
64204
- const newState = state ?? { lastRunMs: 0, inFlight: null };
64205
- if (!state)
64206
- maintenanceStateByRoot.set(rootDir, newState);
64207
- const run = (async () => {
64208
- try {
64209
- await cleanupOldAttachmentFiles(rootDir, opts.ttlMs, opts.log, activeDirsForRoot(rootDir));
64210
- await pruneAttachmentCache(rootDir, opts.maxBytes, opts.log, activeDirsForRoot(rootDir));
64211
- } catch (err) {
64212
- opts.log?.warn?.(`agent-core: attachment cache maintenance failed: ${String(err)}`);
64213
- } finally {
64214
- newState.lastRunMs = Date.now();
64215
- newState.inFlight = null;
64216
- }
64217
- })();
64218
- newState.inFlight = run;
64219
- return run;
64220
- }
64221
- async function ensureAttachmentRootDir(workspaceDir) {
64222
- const workspaceRoot = path9.resolve(workspaceDir);
64223
- const parallDir = path9.join(workspaceRoot, ".parall");
64224
- const rootDir = attachmentRootDir(workspaceRoot);
64225
- await fs7.mkdir(workspaceRoot, { recursive: true });
64226
- await ensurePathIsNotSymlink(parallDir);
64227
- await fs7.mkdir(parallDir, { recursive: true, mode: 448 });
64228
- await ensurePathIsNotSymlink(parallDir);
64229
- await ensurePathIsNotSymlink(rootDir);
64230
- await fs7.mkdir(rootDir, { recursive: true, mode: 448 });
64231
- await ensurePathIsNotSymlink(rootDir);
64232
- const realWorkspace = await fs7.realpath(workspaceRoot);
64233
- const realRoot = await fs7.realpath(rootDir);
64234
- if (!isPathInside(realRoot, realWorkspace)) {
64235
- throw new Error(`attachment root escapes workspace: ${rootDir}`);
64236
- }
64237
- return rootDir;
64238
- }
64239
- async function ensurePathIsNotSymlink(filePath) {
64240
- try {
64241
- const stat2 = await fs7.lstat(filePath);
64242
- if (stat2.isSymbolicLink()) {
64243
- throw new Error(`refusing to use symlinked attachment path ${filePath}`);
64244
- }
64245
- } catch (err) {
64246
- if (err?.code === "ENOENT")
64247
- return;
64248
- throw err;
64249
- }
64250
- }
64251
- function isPathInside(childPath, parentPath) {
64252
- const rel = path9.relative(parentPath, childPath);
64253
- return rel === "" || !!rel && !rel.startsWith("..") && !path9.isAbsolute(rel);
64254
- }
64255
- async function existingUsableFile(filePath, expectedSize, rootDir) {
64256
- try {
64257
- const stat2 = await localFileStatInsideRoot(filePath, rootDir);
64258
- return stat2.isFile() && stat2.size > 0 && (expectedSize <= 0 || stat2.size === expectedSize);
64259
- } catch {
64260
- return false;
64261
- }
64262
- }
64263
- async function localFileStatInsideRoot(filePath, rootDir) {
64264
- const stat2 = await fs7.lstat(filePath);
64265
- if (stat2.isSymbolicLink()) {
64266
- throw new Error(`refusing to use symlinked attachment file ${filePath}`);
64230
+ };
64231
+ var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
64232
+ var JsonRpcStdioClient = class {
64233
+ proc;
64234
+ requestTimeoutMs;
64235
+ killProcess;
64236
+ nextId = 1;
64237
+ pending = /* @__PURE__ */ new Map();
64238
+ buffer = "";
64239
+ onNotification = null;
64240
+ onServerRequest = null;
64241
+ disposed = false;
64242
+ constructor(proc, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, killProcess) {
64243
+ this.proc = proc;
64244
+ this.requestTimeoutMs = requestTimeoutMs;
64245
+ this.killProcess = killProcess;
64246
+ proc.stdout.setEncoding("utf8");
64247
+ proc.stdout.on("data", (chunk) => this.ingest(chunk));
64248
+ proc.once("close", () => this.dispose(new Error("app-server subprocess closed")));
64249
+ proc.once("error", (err) => this.dispose(err));
64250
+ proc.stdin.on("error", (err) => this.killUnhealthy(err));
64267
64251
  }
64268
- if (!stat2.isFile()) {
64269
- throw new Error(`attachment path is not a file ${filePath}`);
64252
+ setNotificationHandler(handler) {
64253
+ this.onNotification = handler;
64270
64254
  }
64271
- const realRoot = await fs7.realpath(rootDir);
64272
- const realFile = await fs7.realpath(filePath);
64273
- if (!isPathInside(realFile, realRoot)) {
64274
- throw new Error(`attachment file escapes workspace: ${filePath}`);
64255
+ setServerRequestHandler(handler) {
64256
+ this.onServerRequest = handler;
64275
64257
  }
64276
- return stat2;
64277
- }
64278
- async function localDirectoryStatInsideRoot(dirPath, rootDir) {
64279
- const stat2 = await fs7.lstat(dirPath);
64280
- if (stat2.isSymbolicLink()) {
64281
- throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
64258
+ /**
64259
+ * `options.timeoutMs` overrides the client-wide budget for this request.
64260
+ * `options.lethalTimeout: false` makes a timeout reject WITHOUT killing the
64261
+ * subprocess — for best-effort side requests (e.g. the compaction watcher's
64262
+ * turn/interrupt) where "no answer" must not translate into a delayed
64263
+ * subprocess kill landing on an unrelated later dispatch. Default (true)
64264
+ * keeps the existing assume-hung semantics.
64265
+ */
64266
+ sendRequest(method, params, options) {
64267
+ if (this.disposed) {
64268
+ return Promise.reject(new Error("JSON-RPC client disposed"));
64269
+ }
64270
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
64271
+ const lethalTimeout = options?.lethalTimeout ?? true;
64272
+ const id = this.nextId++;
64273
+ const request3 = { jsonrpc: "2.0", id, method, params };
64274
+ const promise = new Promise((resolve4, reject) => {
64275
+ const timer = setTimeout(() => {
64276
+ const pending = this.pending.get(id);
64277
+ if (!pending)
64278
+ return;
64279
+ this.pending.delete(id);
64280
+ reject(new Error(`JSON-RPC request "${method}" timed out after ${timeoutMs}ms`));
64281
+ if (lethalTimeout) {
64282
+ this.killUnhealthy(new Error(`request "${method}" timed out; subprocess assumed hung`));
64283
+ }
64284
+ }, timeoutMs);
64285
+ this.pending.set(id, { resolve: resolve4, reject, timer });
64286
+ });
64287
+ this.writeFrame(request3);
64288
+ return promise;
64282
64289
  }
64283
- if (!stat2.isDirectory()) {
64284
- throw new Error(`attachment path is not a directory ${dirPath}`);
64290
+ sendNotification(method, params) {
64291
+ if (this.disposed)
64292
+ return;
64293
+ const notification = { jsonrpc: "2.0", method, params };
64294
+ this.writeFrame(notification);
64285
64295
  }
64286
- const realRoot = await fs7.realpath(rootDir);
64287
- const realDir = await fs7.realpath(dirPath);
64288
- if (!isPathInside(realDir, realRoot)) {
64289
- throw new Error(`attachment directory escapes workspace: ${dirPath}`);
64296
+ isDisposed() {
64297
+ return this.disposed;
64290
64298
  }
64291
- return stat2;
64292
- }
64293
- async function openLocalFileInsideRoot(filePath, rootDir) {
64294
- const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
64295
- const file = await fs7.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
64296
- let keepOpen = false;
64297
- try {
64298
- const openedStat = await file.stat();
64299
- if (!sameFile(checkedStat, openedStat)) {
64300
- throw new Error(`attachment file changed during validation: ${filePath}`);
64301
- }
64302
- keepOpen = true;
64303
- return file;
64304
- } finally {
64305
- if (!keepOpen) {
64306
- await file.close();
64299
+ dispose(err) {
64300
+ if (this.disposed)
64301
+ return;
64302
+ this.disposed = true;
64303
+ for (const pending of this.pending.values()) {
64304
+ clearTimeout(pending.timer);
64305
+ pending.reject(err);
64307
64306
  }
64307
+ this.pending.clear();
64308
64308
  }
64309
- }
64310
- async function openLocalTempFileInsideRoot(filePath, rootDir) {
64311
- await localDirectoryStatInsideRoot(path9.dirname(filePath), rootDir);
64312
- const file = await fs7.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
64313
- let keepOpen = false;
64314
- try {
64315
- const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
64316
- const openedStat = await file.stat();
64317
- if (!sameFileIdentity(checkedStat, openedStat)) {
64318
- throw new Error(`attachment temp file changed during validation: ${filePath}`);
64319
- }
64320
- keepOpen = true;
64321
- return { file, openedStat };
64322
- } finally {
64323
- if (!keepOpen) {
64324
- await file.close();
64309
+ writeFrame(message) {
64310
+ try {
64311
+ this.proc.stdin.write(`${JSON.stringify(message)}
64312
+ `);
64313
+ } catch (err) {
64314
+ this.killUnhealthy(err instanceof Error ? err : new Error(String(err)));
64325
64315
  }
64326
64316
  }
64327
- }
64328
- async function assertLocalFileIdentity(filePath, rootDir, expected) {
64329
- const stat2 = await localFileStatInsideRoot(filePath, rootDir);
64330
- if (!sameFileIdentity(stat2, expected)) {
64331
- throw new Error(`attachment file changed during validation: ${filePath}`);
64332
- }
64333
- }
64334
- async function removeLocalFileIfInside(filePath, rootDir) {
64335
- try {
64336
- await localFileStatInsideRoot(filePath, rootDir);
64337
- await fs7.rm(filePath, { force: true });
64338
- } catch {
64317
+ killUnhealthy(err) {
64318
+ this.dispose(err);
64319
+ if (this.proc.exitCode === null && this.proc.signalCode === null) {
64320
+ if (this.killProcess) {
64321
+ this.killProcess(this.proc);
64322
+ } else {
64323
+ this.proc.kill("SIGTERM");
64324
+ }
64325
+ }
64339
64326
  }
64340
- }
64341
- function sameFileIdentity(a, b) {
64342
- return a.dev === b.dev && a.ino === b.ino;
64343
- }
64344
- function sameFile(a, b) {
64345
- return sameFileIdentity(a, b) && a.size === b.size && a.mtimeMs === b.mtimeMs;
64346
- }
64347
- async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
64348
- let entries;
64349
- try {
64350
- entries = await fs7.readdir(rootDir, { withFileTypes: true });
64351
- } catch {
64352
- return;
64327
+ ingest(chunk) {
64328
+ this.buffer += chunk;
64329
+ let newlineIndex = this.buffer.indexOf("\n");
64330
+ while (newlineIndex >= 0) {
64331
+ const line = this.buffer.slice(0, newlineIndex).trim();
64332
+ this.buffer = this.buffer.slice(newlineIndex + 1);
64333
+ if (line)
64334
+ this.handleLine(line);
64335
+ newlineIndex = this.buffer.indexOf("\n");
64336
+ }
64353
64337
  }
64354
- const cutoff = Date.now() - ttlMs;
64355
- await Promise.all(entries.map(async (entry) => {
64356
- if (!entry.isDirectory())
64357
- return;
64358
- const fullPath = path9.join(rootDir, entry.name);
64338
+ handleLine(line) {
64339
+ let message;
64359
64340
  try {
64360
- if (preserveDirs?.has(path9.resolve(fullPath)))
64361
- return;
64362
- const stat2 = await fs7.lstat(fullPath);
64363
- if (!stat2.isDirectory())
64341
+ message = JSON.parse(line);
64342
+ } catch {
64343
+ return;
64344
+ }
64345
+ if (isResponse(message)) {
64346
+ const pending = this.pending.get(message.id);
64347
+ if (!pending)
64364
64348
  return;
64365
- if (stat2.mtimeMs < cutoff) {
64366
- await fs7.rm(fullPath, { recursive: true, force: true });
64349
+ this.pending.delete(message.id);
64350
+ clearTimeout(pending.timer);
64351
+ if (message.error) {
64352
+ pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
64353
+ } else {
64354
+ pending.resolve(message.result);
64367
64355
  }
64368
- } catch (err) {
64369
- log2?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
64356
+ return;
64370
64357
  }
64371
- }));
64372
- }
64373
- async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
64374
- if (maxBytes <= 0)
64375
- return;
64376
- let entries;
64377
- try {
64378
- entries = await fs7.readdir(rootDir, { withFileTypes: true });
64379
- } catch {
64380
- return;
64381
- }
64382
- const dirs = [];
64383
- let total = 0;
64384
- for (const entry of entries) {
64385
- if (!entry.isDirectory())
64386
- continue;
64387
- const fullPath = path9.join(rootDir, entry.name);
64388
- try {
64389
- const stat2 = await fs7.lstat(fullPath);
64390
- if (!stat2.isDirectory())
64391
- continue;
64392
- const size = await directorySize(fullPath);
64393
- dirs.push({ path: fullPath, mtimeMs: stat2.mtimeMs, size });
64394
- total += size;
64395
- } catch (err) {
64396
- log2?.warn?.(`agent-core: failed to inspect attachment cache dir ${fullPath}: ${String(err)}`);
64358
+ if (isServerRequest(message)) {
64359
+ this.answerServerRequest(message);
64360
+ return;
64397
64361
  }
64398
- }
64399
- if (total <= maxBytes)
64400
- return;
64401
- dirs.sort((a, b) => a.mtimeMs - b.mtimeMs);
64402
- for (const dir of dirs) {
64403
- if (total <= maxBytes)
64404
- break;
64405
- if (preserveDirs?.has(path9.resolve(dir.path)))
64406
- continue;
64407
- try {
64408
- await fs7.rm(dir.path, { recursive: true, force: true });
64409
- total -= dir.size;
64410
- } catch (err) {
64411
- log2?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
64362
+ if (isNotification(message)) {
64363
+ this.onNotification?.(message.method, message.params);
64412
64364
  }
64413
64365
  }
64414
- }
64415
- async function directorySize(dirPath) {
64416
- let total = 0;
64417
- const entries = await fs7.readdir(dirPath, { withFileTypes: true });
64418
- for (const entry of entries) {
64419
- const fullPath = path9.join(dirPath, entry.name);
64420
- let stat2;
64366
+ answerServerRequest(request3) {
64367
+ let answer;
64421
64368
  try {
64422
- stat2 = await fs7.lstat(fullPath);
64423
- } catch {
64424
- continue;
64369
+ answer = this.onServerRequest?.(request3.method, request3.params);
64370
+ } catch (err) {
64371
+ this.writeFrame({
64372
+ jsonrpc: "2.0",
64373
+ id: request3.id,
64374
+ error: { code: -32603, message: `server request handler failed: ${String(err)}` }
64375
+ });
64376
+ return;
64425
64377
  }
64426
- if (stat2.isDirectory()) {
64427
- total += await directorySize(fullPath);
64428
- continue;
64378
+ if (answer !== void 0) {
64379
+ this.writeFrame({
64380
+ jsonrpc: "2.0",
64381
+ id: request3.id,
64382
+ result: answer.result === void 0 ? null : answer.result
64383
+ });
64384
+ return;
64429
64385
  }
64430
- if (!stat2.isFile())
64431
- continue;
64432
- total += stat2.size;
64386
+ this.writeFrame({
64387
+ jsonrpc: "2.0",
64388
+ id: request3.id,
64389
+ error: { code: -32601, message: `unsupported server request: ${request3.method}` }
64390
+ });
64433
64391
  }
64434
- return total;
64392
+ };
64393
+ function isResponse(m) {
64394
+ return !!m && typeof m === "object" && "id" in m && ("result" in m || "error" in m);
64435
64395
  }
64436
- function activeDirsForRoot(rootDir) {
64437
- const root = path9.resolve(rootDir);
64438
- const dirs = /* @__PURE__ */ new Set();
64439
- for (const dir of activeAttachmentDirs) {
64440
- if (dir === root || dir.startsWith(`${root}${path9.sep}`)) {
64441
- dirs.add(dir);
64442
- }
64443
- }
64444
- return dirs;
64396
+ function isServerRequest(m) {
64397
+ return !!m && typeof m === "object" && "method" in m && "id" in m;
64445
64398
  }
64446
- async function downloadAttachmentToFile(url, filePath, maxBytes, timeoutMs, rootDir) {
64447
- let parsed;
64448
- try {
64449
- parsed = new URL(url);
64450
- } catch {
64451
- throw new Error(`invalid attachment URL`);
64452
- }
64453
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
64454
- throw new Error(`refusing attachment URL with scheme ${parsed.protocol}`);
64455
- }
64456
- const controller = new AbortController();
64457
- let timeout;
64458
- if (timeoutMs > 0) {
64459
- timeout = setTimeout(() => controller.abort(), timeoutMs);
64460
- }
64399
+ function isNotification(m) {
64400
+ return !!m && typeof m === "object" && "method" in m && !("id" in m);
64401
+ }
64402
+
64403
+ // ts/codex-agent/dist/start-input.js
64404
+ async function startCodexInput(opts) {
64405
+ const { client, receipts, sink, sessionKey, threadId, inputLifecycle, input, model, effort, log: log2 } = opts;
64406
+ if (sink.input)
64407
+ receipts.forget(sink.input);
64408
+ sink.input = receipts.register(sessionKey, threadId, inputLifecycle);
64409
+ const turnParams = {
64410
+ threadId,
64411
+ input,
64412
+ clientUserMessageId: sink.input.clientId
64413
+ };
64414
+ if (model)
64415
+ turnParams.model = model;
64416
+ if (effort)
64417
+ turnParams.effort = effort;
64461
64418
  try {
64462
- const res = await fetch(url, { signal: controller.signal });
64463
- if (!res.ok) {
64464
- throw new Error(`${res.status} ${res.statusText}`);
64465
- }
64466
- const contentLength = parseContentLength(res.headers.get("content-length"));
64467
- if (contentLength !== void 0 && contentLength > maxBytes) {
64468
- throw new Error(`download would exceed ${formatBytes(maxBytes)} remaining turn limit`);
64469
- }
64470
- return await writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir);
64419
+ return extractTurnId(await client.sendRequest("turn/start", turnParams));
64471
64420
  } catch (err) {
64472
- if (isAbortError(err)) {
64473
- throw new Error(`download timed out after ${timeoutMs}ms`);
64421
+ if (!(err instanceof JsonRpcError)) {
64422
+ log2?.warn?.(`Codex turn/start response uncertain; retaining input observation: ${errToString(err)}`);
64423
+ await sink.waitForInputOrClose();
64474
64424
  }
64475
- throw err;
64476
- } finally {
64477
- if (timeout)
64478
- clearTimeout(timeout);
64425
+ if (!sink.input.observed || !sink.input.turnId)
64426
+ throw err;
64427
+ log2?.warn?.(`Codex turn/start response failed after input application: ${errToString(err)}`);
64428
+ return sink.input.turnId;
64479
64429
  }
64480
64430
  }
64481
- async function withTimeout(promise, timeoutMs, message) {
64482
- if (timeoutMs <= 0)
64483
- return promise;
64484
- let timeout;
64485
- try {
64486
- return await Promise.race([
64487
- promise,
64488
- new Promise((_, reject) => {
64489
- timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
64490
- })
64491
- ]);
64492
- } finally {
64493
- if (timeout)
64494
- clearTimeout(timeout);
64495
- }
64431
+ function errToString(err) {
64432
+ return err instanceof Error ? err.message : String(err);
64496
64433
  }
64497
- async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
64498
- if (maxBytes <= 0) {
64499
- throw new Error("download would exceed turn limit");
64434
+
64435
+ // ts/codex-agent/dist/dispatch.js
64436
+ import { spawn } from "node:child_process";
64437
+ import { randomUUID as randomUUID7 } from "node:crypto";
64438
+ import * as path11 from "node:path";
64439
+
64440
+ // ts/agent-core/dist/internal/attachment-input.js
64441
+ import { execSync } from "node:child_process";
64442
+ import { constants } from "node:fs";
64443
+ import * as fsSync from "node:fs";
64444
+ import * as fs7 from "node:fs/promises";
64445
+ import * as path9 from "node:path";
64446
+ var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
64447
+ var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
64448
+ var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
64449
+ var DEFAULT_ATTACHMENT_TTL_MS = 24 * 60 * 60 * 1e3;
64450
+ var DEFAULT_MAINTENANCE_COOLDOWN_MS = 60 * 1e3;
64451
+ var SUPPORTED_IMAGE_MIME_TYPES = /* @__PURE__ */ new Set([
64452
+ "image/png",
64453
+ "image/jpeg",
64454
+ "image/jpg",
64455
+ "image/webp",
64456
+ "image/gif"
64457
+ ]);
64458
+ var activeAttachmentDirs = /* @__PURE__ */ new Set();
64459
+ async function prepareLocalImageAttachments(event, context2, opts) {
64460
+ const attachments = event.attachments ?? [];
64461
+ const imageAttachments = attachments.filter((att) => SUPPORTED_IMAGE_MIME_TYPES.has(att.mimeType.toLowerCase()));
64462
+ if (imageAttachments.length === 0)
64463
+ return { images: [], notes: [] };
64464
+ const maxTotalImageBytes = opts.maxTotalImageBytes ?? DEFAULT_MAX_TOTAL_IMAGE_BYTES;
64465
+ const totalDeclaredBytes = imageAttachments.reduce((sum, att) => sum + Math.max(0, att.fileSize), 0);
64466
+ if (totalDeclaredBytes > maxTotalImageBytes) {
64467
+ return {
64468
+ images: [],
64469
+ notes: [
64470
+ `[Image attachments not downloaded: total size ${formatBytes(totalDeclaredBytes)} exceeds bridge limit ${formatBytes(maxTotalImageBytes)}]`
64471
+ ]
64472
+ };
64473
+ }
64474
+ const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
64475
+ const messageDir = path9.join(rootDir, sanitizePathSegment(event.messageId));
64476
+ await ensurePathIsNotSymlink(messageDir);
64477
+ await fs7.mkdir(messageDir, { recursive: true });
64478
+ await ensurePathIsNotSymlink(messageDir);
64479
+ const activeMessageDir = path9.resolve(messageDir);
64480
+ activeAttachmentDirs.add(activeMessageDir);
64481
+ const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
64482
+ const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
64483
+ ttlMs: opts.attachmentTtlMs ?? DEFAULT_ATTACHMENT_TTL_MS,
64484
+ maxBytes: opts.maxCacheBytes ?? DEFAULT_ATTACHMENT_CACHE_MAX_BYTES,
64485
+ cooldownMs: maintenanceCooldownMs,
64486
+ log: opts.log
64487
+ });
64488
+ if (maintenanceCooldownMs === 0 && maintenancePromise) {
64489
+ await maintenancePromise;
64500
64490
  }
64501
- const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
64502
- const { file, openedStat } = await openLocalTempFileInsideRoot(tmpPath, rootDir);
64503
- let written = 0;
64504
- let completed = false;
64505
- let fileClosed = false;
64506
- let writtenStat = openedStat;
64507
- const closeFile = async () => {
64508
- if (fileClosed)
64509
- return;
64510
- await file.close();
64511
- fileClosed = true;
64512
- };
64513
64491
  try {
64514
- if (!res.body) {
64515
- const buffer = Buffer.from(await res.arrayBuffer());
64516
- if (buffer.byteLength > maxBytes) {
64517
- throw new Error(`download exceeded ${formatBytes(maxBytes)} remaining turn limit`);
64492
+ const images = [];
64493
+ const notes = [];
64494
+ let downloadedBytes = 0;
64495
+ for (const att of imageAttachments) {
64496
+ const localPath = path9.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
64497
+ const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
64498
+ const fetchFresh = async () => {
64499
+ const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
64500
+ downloadedBytes += await downloadAttachmentToFile(fileInfo.url, localPath, maxTotalImageBytes - downloadedBytes, downloadTimeoutMs, rootDir);
64501
+ };
64502
+ const cameFromCache = await existingUsableFile(localPath, att.fileSize, rootDir);
64503
+ if (!cameFromCache) {
64504
+ try {
64505
+ await fetchFresh();
64506
+ } catch (err) {
64507
+ opts.log?.warn?.(`agent-core: failed to prepare local image attachment ${att.id}: ${String(err)}`);
64508
+ notes.push(`[Image attachment unavailable locally: prll://${sanitizeMeta2(att.id)}]`);
64509
+ continue;
64510
+ }
64518
64511
  }
64519
- await file.write(buffer);
64520
- written = buffer.byteLength;
64521
- } else {
64522
- const reader = res.body.getReader();
64523
- while (true) {
64524
- const { done, value } = await reader.read();
64525
- if (done)
64526
- break;
64527
- const chunk = Buffer.from(value);
64528
- written += chunk.byteLength;
64529
- if (written > maxBytes) {
64530
- throw new Error(`download exceeded ${formatBytes(maxBytes)} remaining turn limit`);
64512
+ let mimeOk = await downloadedFileMatchesImageMime(localPath, att.mimeType, rootDir);
64513
+ if (!mimeOk && cameFromCache) {
64514
+ await removeLocalFileIfInside(localPath, rootDir);
64515
+ try {
64516
+ await fetchFresh();
64517
+ } catch (err) {
64518
+ opts.log?.warn?.(`agent-core: failed to re-download corrupted cache for ${att.id}: ${String(err)}`);
64519
+ notes.push(`[Image attachment unavailable locally: prll://${sanitizeMeta2(att.id)}]`);
64520
+ continue;
64531
64521
  }
64532
- await file.write(chunk);
64522
+ mimeOk = await downloadedFileMatchesImageMime(localPath, att.mimeType, rootDir);
64533
64523
  }
64534
- }
64535
- writtenStat = await file.stat();
64536
- await closeFile();
64537
- await localDirectoryStatInsideRoot(path9.dirname(filePath), rootDir);
64538
- await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
64539
- await fs7.rename(tmpPath, filePath);
64540
- completed = true;
64541
- return written;
64542
- } finally {
64543
- if (!fileClosed) {
64544
- try {
64545
- await closeFile();
64546
- } catch {
64524
+ if (!mimeOk) {
64525
+ await removeLocalFileIfInside(localPath, rootDir);
64526
+ notes.push(`[Image attachment unavailable locally: prll://${sanitizeMeta2(att.id)} (downloaded content does not match ${sanitizeMeta2(att.mimeType)})]`);
64527
+ continue;
64547
64528
  }
64529
+ images.push({
64530
+ attachmentId: att.id,
64531
+ fileName: att.fileName,
64532
+ mimeType: att.mimeType,
64533
+ fileSize: att.fileSize,
64534
+ localPath
64535
+ });
64548
64536
  }
64549
- if (!completed) {
64550
- await removeLocalFileIfInside(tmpPath, rootDir);
64551
- }
64537
+ return { images, notes };
64538
+ } finally {
64539
+ activeAttachmentDirs.delete(activeMessageDir);
64552
64540
  }
64553
64541
  }
64554
- function localFileName(attachmentId, fileName, mimeType) {
64555
- const safeName = sanitizePathSegment(path9.basename(fileName || attachmentId));
64556
- const ext = path9.extname(safeName) || extensionForMime(mimeType);
64557
- const stem = path9.basename(safeName, path9.extname(safeName)) || attachmentId;
64558
- return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
64542
+ function appendLocalAttachmentRefs(body, result) {
64543
+ const section = renderLocalAttachmentSection(result);
64544
+ return section ? `${body}
64545
+
64546
+ ${section}` : body;
64559
64547
  }
64560
- function extensionForMime(mimeType) {
64561
- switch (mimeType.toLowerCase()) {
64562
- case "image/jpeg":
64563
- case "image/jpg":
64564
- return ".jpg";
64565
- case "image/webp":
64566
- return ".webp";
64567
- case "image/gif":
64568
- return ".gif";
64569
- case "image/png":
64570
- default:
64571
- return ".png";
64548
+ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
64549
+ const attachments = await prepareLocalImageAttachments(event, context2, opts);
64550
+ return { body: appendLocalAttachmentRefs(body, attachments), attachments };
64551
+ }
64552
+ function pinLocalAttachmentPaths(images) {
64553
+ const dirs = new Set(images.map((image) => path9.resolve(path9.dirname(image.localPath))));
64554
+ for (const dir of dirs) {
64555
+ activeAttachmentDirs.add(dir);
64572
64556
  }
64557
+ let released = false;
64558
+ return () => {
64559
+ if (released)
64560
+ return;
64561
+ released = true;
64562
+ for (const dir of dirs) {
64563
+ activeAttachmentDirs.delete(dir);
64564
+ }
64565
+ };
64573
64566
  }
64574
- function sanitizePathSegment(value) {
64575
- const safe = value.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
64576
- if (!safe || /^\.+$/.test(safe))
64577
- return "attachment";
64578
- return safe;
64567
+ function attachmentRootDir(workspaceDir) {
64568
+ return path9.join(path9.resolve(workspaceDir), ".parall", "attachments");
64579
64569
  }
64580
- async function downloadedFileMatchesImageMime(filePath, mimeType, rootDir) {
64581
- const file = await openLocalFileInsideRoot(filePath, rootDir);
64570
+ function ensureLocalAttachmentGitExclude(workingDirectory) {
64582
64571
  try {
64583
- const buffer = Buffer.alloc(16);
64584
- const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
64585
- return imageHeaderMatches(buffer.subarray(0, bytesRead), mimeType);
64586
- } finally {
64587
- await file.close();
64588
- }
64589
- }
64590
- function imageHeaderMatches(bytes, mimeType) {
64591
- switch (mimeType.toLowerCase()) {
64592
- case "image/png":
64593
- return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10;
64594
- case "image/jpeg":
64595
- case "image/jpg":
64596
- return bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
64597
- case "image/gif":
64598
- return bytes.length >= 6 && (bytes.subarray(0, 6).toString("ascii") === "GIF87a" || bytes.subarray(0, 6).toString("ascii") === "GIF89a");
64599
- case "image/webp":
64600
- return bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
64601
- default:
64602
- return false;
64572
+ const rel = execSync("git rev-parse --git-path info/exclude", {
64573
+ cwd: workingDirectory,
64574
+ encoding: "utf8",
64575
+ stdio: ["ignore", "pipe", "ignore"]
64576
+ }).trim();
64577
+ const excludePath = path9.isAbsolute(rel) ? rel : path9.join(workingDirectory, rel);
64578
+ fsSync.mkdirSync(path9.dirname(excludePath), { recursive: true });
64579
+ const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
64580
+ if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
64581
+ return;
64582
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
64583
+ fsSync.appendFileSync(excludePath, `${prefix}.parall/
64584
+ `, "utf8");
64585
+ } catch {
64603
64586
  }
64604
64587
  }
64605
- function isAbortError(err) {
64606
- return err instanceof DOMException && err.name === "AbortError";
64607
- }
64608
- function sanitizeMeta2(value) {
64609
- return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
64588
+ var maintenanceStateByRoot = /* @__PURE__ */ new Map();
64589
+ function scheduleAttachmentMaintenance(rootDir, opts) {
64590
+ const state = maintenanceStateByRoot.get(rootDir);
64591
+ if (state?.inFlight)
64592
+ return state.inFlight;
64593
+ const now = Date.now();
64594
+ if (state && now - state.lastRunMs < opts.cooldownMs)
64595
+ return null;
64596
+ const newState = state ?? { lastRunMs: 0, inFlight: null };
64597
+ if (!state)
64598
+ maintenanceStateByRoot.set(rootDir, newState);
64599
+ const run = (async () => {
64600
+ try {
64601
+ await cleanupOldAttachmentFiles(rootDir, opts.ttlMs, opts.log, activeDirsForRoot(rootDir));
64602
+ await pruneAttachmentCache(rootDir, opts.maxBytes, opts.log, activeDirsForRoot(rootDir));
64603
+ } catch (err) {
64604
+ opts.log?.warn?.(`agent-core: attachment cache maintenance failed: ${String(err)}`);
64605
+ } finally {
64606
+ newState.lastRunMs = Date.now();
64607
+ newState.inFlight = null;
64608
+ }
64609
+ })();
64610
+ newState.inFlight = run;
64611
+ return run;
64610
64612
  }
64611
- function parseContentLength(value) {
64612
- if (!value)
64613
- return void 0;
64614
- const n = Number(value);
64615
- if (!Number.isFinite(n) || n < 0)
64616
- return void 0;
64617
- return n;
64613
+ async function ensureAttachmentRootDir(workspaceDir) {
64614
+ const workspaceRoot = path9.resolve(workspaceDir);
64615
+ const parallDir = path9.join(workspaceRoot, ".parall");
64616
+ const rootDir = attachmentRootDir(workspaceRoot);
64617
+ await fs7.mkdir(workspaceRoot, { recursive: true });
64618
+ await ensurePathIsNotSymlink(parallDir);
64619
+ await fs7.mkdir(parallDir, { recursive: true, mode: 448 });
64620
+ await ensurePathIsNotSymlink(parallDir);
64621
+ await ensurePathIsNotSymlink(rootDir);
64622
+ await fs7.mkdir(rootDir, { recursive: true, mode: 448 });
64623
+ await ensurePathIsNotSymlink(rootDir);
64624
+ const realWorkspace = await fs7.realpath(workspaceRoot);
64625
+ const realRoot = await fs7.realpath(rootDir);
64626
+ if (!isPathInside(realRoot, realWorkspace)) {
64627
+ throw new Error(`attachment root escapes workspace: ${rootDir}`);
64628
+ }
64629
+ return rootDir;
64618
64630
  }
64619
-
64620
- // ts/codex-agent/dist/app-server-process.js
64621
- import { execSync as execSync2 } from "node:child_process";
64622
- import * as fs8 from "node:fs";
64623
- var IS_WIN32 = process.platform === "win32";
64624
- function quoteWin32Arg(arg) {
64625
- if (!/[\s"&|^<>()]/.test(arg))
64626
- return arg;
64627
- return `"${arg.replace(/"/g, '""')}"`;
64631
+ async function ensurePathIsNotSymlink(filePath) {
64632
+ try {
64633
+ const stat2 = await fs7.lstat(filePath);
64634
+ if (stat2.isSymbolicLink()) {
64635
+ throw new Error(`refusing to use symlinked attachment path ${filePath}`);
64636
+ }
64637
+ } catch (err) {
64638
+ if (err?.code === "ENOENT")
64639
+ return;
64640
+ throw err;
64641
+ }
64628
64642
  }
64629
- function killWin32Tree(pid) {
64643
+ function isPathInside(childPath, parentPath) {
64644
+ const rel = path9.relative(parentPath, childPath);
64645
+ return rel === "" || !!rel && !rel.startsWith("..") && !path9.isAbsolute(rel);
64646
+ }
64647
+ async function existingUsableFile(filePath, expectedSize, rootDir) {
64630
64648
  try {
64631
- execSync2(`taskkill /T /F /PID ${pid}`, { windowsHide: true, stdio: "ignore" });
64632
- return true;
64649
+ const stat2 = await localFileStatInsideRoot(filePath, rootDir);
64650
+ return stat2.isFile() && stat2.size > 0 && (expectedSize <= 0 || stat2.size === expectedSize);
64633
64651
  } catch {
64634
64652
  return false;
64635
64653
  }
64636
64654
  }
64637
- function ensureGitRepo(workingDirectory) {
64638
- fs8.mkdirSync(workingDirectory, { recursive: true });
64639
- try {
64640
- execSync2("git rev-parse --is-inside-work-tree", { cwd: workingDirectory, stdio: "pipe" });
64641
- ensureLocalAttachmentGitExclude(workingDirectory);
64642
- return;
64643
- } catch {
64655
+ async function localFileStatInsideRoot(filePath, rootDir) {
64656
+ const stat2 = await fs7.lstat(filePath);
64657
+ if (stat2.isSymbolicLink()) {
64658
+ throw new Error(`refusing to use symlinked attachment file ${filePath}`);
64644
64659
  }
64645
- const env = {
64646
- ...process.env,
64647
- GIT_AUTHOR_NAME: "parall-codex-agent",
64648
- GIT_AUTHOR_EMAIL: "agent@parall.local",
64649
- GIT_COMMITTER_NAME: "parall-codex-agent",
64650
- GIT_COMMITTER_EMAIL: "agent@parall.local"
64651
- };
64652
- try {
64653
- execSync2("git init", { cwd: workingDirectory, stdio: "pipe", env });
64654
- execSync2("git commit --allow-empty -m init", { cwd: workingDirectory, stdio: "pipe", env });
64655
- ensureLocalAttachmentGitExclude(workingDirectory);
64656
- } catch {
64660
+ if (!stat2.isFile()) {
64661
+ throw new Error(`attachment path is not a file ${filePath}`);
64657
64662
  }
64663
+ const realRoot = await fs7.realpath(rootDir);
64664
+ const realFile = await fs7.realpath(filePath);
64665
+ if (!isPathInside(realFile, realRoot)) {
64666
+ throw new Error(`attachment file escapes workspace: ${filePath}`);
64667
+ }
64668
+ return stat2;
64658
64669
  }
64659
-
64660
- // ts/codex-agent/dist/app-server-protocol.js
64661
- function buildTurnInput(body, images) {
64662
- return [
64663
- { type: "text", text: body },
64664
- ...images.map((image) => ({ type: "localImage", path: image.localPath }))
64665
- ];
64666
- }
64667
- function extractThreadId(result) {
64668
- if (!result || typeof result !== "object")
64669
- return void 0;
64670
- const r = result;
64671
- if (typeof r.threadId === "string")
64672
- return r.threadId;
64673
- const thread = r.thread;
64674
- if (thread && typeof thread.id === "string")
64675
- return thread.id;
64676
- return void 0;
64677
- }
64678
- function extractTurnId(result) {
64679
- if (!result || typeof result !== "object")
64680
- return void 0;
64681
- const r = result;
64682
- if (typeof r.turnId === "string")
64683
- return r.turnId;
64684
- const turn = r.turn;
64685
- if (turn && typeof turn.id === "string")
64686
- return turn.id;
64687
- return void 0;
64688
- }
64689
- function extractThreadInfo(params) {
64690
- if (!params || typeof params !== "object")
64691
- return void 0;
64692
- const p = params;
64693
- const thread = p.thread && typeof p.thread === "object" ? p.thread : p;
64694
- const id = typeof thread.id === "string" ? thread.id : typeof p.threadId === "string" ? p.threadId : void 0;
64695
- if (!id)
64696
- return void 0;
64697
- const str = (value) => typeof value === "string" && value.trim() ? value : void 0;
64698
- return {
64699
- id,
64700
- parentThreadId: str(thread.parentThreadId),
64701
- source: str(thread.threadSource) ?? str(thread.source),
64702
- nickname: str(thread.agentNickname),
64703
- role: str(thread.agentRole)
64704
- };
64705
- }
64706
- function extractThreadIdFromNotification(params) {
64707
- if (!params || typeof params !== "object")
64708
- return void 0;
64709
- const p = params;
64710
- if (typeof p.threadId === "string")
64711
- return p.threadId;
64712
- const thread = p.thread;
64713
- if (thread && typeof thread.id === "string")
64714
- return thread.id;
64715
- const meta = p._meta ?? p.meta;
64716
- if (meta && typeof meta.threadId === "string")
64717
- return meta.threadId;
64718
- return void 0;
64719
- }
64720
-
64721
- // ts/codex-agent/dist/instructions-refresh.js
64722
- import { createHash } from "node:crypto";
64723
-
64724
- // ts/codex-agent/dist/jsonrpc-client.js
64725
- var JSON_RPC_METHOD_NOT_FOUND = -32601;
64726
- var JsonRpcError = class extends Error {
64727
- code;
64728
- data;
64729
- constructor(code, message, data) {
64730
- super(message || "JSON-RPC error");
64731
- this.code = code;
64732
- this.data = data;
64733
- this.name = "JsonRpcError";
64670
+ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
64671
+ const stat2 = await fs7.lstat(dirPath);
64672
+ if (stat2.isSymbolicLink()) {
64673
+ throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
64734
64674
  }
64735
- };
64736
- var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
64737
- var JsonRpcStdioClient = class {
64738
- proc;
64739
- requestTimeoutMs;
64740
- killProcess;
64741
- nextId = 1;
64742
- pending = /* @__PURE__ */ new Map();
64743
- buffer = "";
64744
- onNotification = null;
64745
- onServerRequest = null;
64746
- disposed = false;
64747
- constructor(proc, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, killProcess) {
64748
- this.proc = proc;
64749
- this.requestTimeoutMs = requestTimeoutMs;
64750
- this.killProcess = killProcess;
64751
- proc.stdout.setEncoding("utf8");
64752
- proc.stdout.on("data", (chunk) => this.ingest(chunk));
64753
- proc.once("close", () => this.dispose(new Error("app-server subprocess closed")));
64754
- proc.once("error", (err) => this.dispose(err));
64755
- proc.stdin.on("error", (err) => this.killUnhealthy(err));
64675
+ if (!stat2.isDirectory()) {
64676
+ throw new Error(`attachment path is not a directory ${dirPath}`);
64756
64677
  }
64757
- setNotificationHandler(handler) {
64758
- this.onNotification = handler;
64678
+ const realRoot = await fs7.realpath(rootDir);
64679
+ const realDir = await fs7.realpath(dirPath);
64680
+ if (!isPathInside(realDir, realRoot)) {
64681
+ throw new Error(`attachment directory escapes workspace: ${dirPath}`);
64759
64682
  }
64760
- setServerRequestHandler(handler) {
64761
- this.onServerRequest = handler;
64683
+ return stat2;
64684
+ }
64685
+ async function openLocalFileInsideRoot(filePath, rootDir) {
64686
+ const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
64687
+ const file = await fs7.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
64688
+ let keepOpen = false;
64689
+ try {
64690
+ const openedStat = await file.stat();
64691
+ if (!sameFile(checkedStat, openedStat)) {
64692
+ throw new Error(`attachment file changed during validation: ${filePath}`);
64693
+ }
64694
+ keepOpen = true;
64695
+ return file;
64696
+ } finally {
64697
+ if (!keepOpen) {
64698
+ await file.close();
64699
+ }
64762
64700
  }
64763
- /**
64764
- * `options.timeoutMs` overrides the client-wide budget for this request.
64765
- * `options.lethalTimeout: false` makes a timeout reject WITHOUT killing the
64766
- * subprocess — for best-effort side requests (e.g. the compaction watcher's
64767
- * turn/interrupt) where "no answer" must not translate into a delayed
64768
- * subprocess kill landing on an unrelated later dispatch. Default (true)
64769
- * keeps the existing assume-hung semantics.
64770
- */
64771
- sendRequest(method, params, options) {
64772
- if (this.disposed) {
64773
- return Promise.reject(new Error("JSON-RPC client disposed"));
64701
+ }
64702
+ async function openLocalTempFileInsideRoot(filePath, rootDir) {
64703
+ await localDirectoryStatInsideRoot(path9.dirname(filePath), rootDir);
64704
+ const file = await fs7.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
64705
+ let keepOpen = false;
64706
+ try {
64707
+ const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
64708
+ const openedStat = await file.stat();
64709
+ if (!sameFileIdentity(checkedStat, openedStat)) {
64710
+ throw new Error(`attachment temp file changed during validation: ${filePath}`);
64711
+ }
64712
+ keepOpen = true;
64713
+ return { file, openedStat };
64714
+ } finally {
64715
+ if (!keepOpen) {
64716
+ await file.close();
64774
64717
  }
64775
- const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
64776
- const lethalTimeout = options?.lethalTimeout ?? true;
64777
- const id = this.nextId++;
64778
- const request3 = { jsonrpc: "2.0", id, method, params };
64779
- const promise = new Promise((resolve4, reject) => {
64780
- const timer = setTimeout(() => {
64781
- const pending = this.pending.get(id);
64782
- if (!pending)
64783
- return;
64784
- this.pending.delete(id);
64785
- reject(new Error(`JSON-RPC request "${method}" timed out after ${timeoutMs}ms`));
64786
- if (lethalTimeout) {
64787
- this.killUnhealthy(new Error(`request "${method}" timed out; subprocess assumed hung`));
64788
- }
64789
- }, timeoutMs);
64790
- this.pending.set(id, { resolve: resolve4, reject, timer });
64791
- });
64792
- this.writeFrame(request3);
64793
- return promise;
64794
64718
  }
64795
- sendNotification(method, params) {
64796
- if (this.disposed)
64797
- return;
64798
- const notification = { jsonrpc: "2.0", method, params };
64799
- this.writeFrame(notification);
64719
+ }
64720
+ async function assertLocalFileIdentity(filePath, rootDir, expected) {
64721
+ const stat2 = await localFileStatInsideRoot(filePath, rootDir);
64722
+ if (!sameFileIdentity(stat2, expected)) {
64723
+ throw new Error(`attachment file changed during validation: ${filePath}`);
64800
64724
  }
64801
- isDisposed() {
64802
- return this.disposed;
64725
+ }
64726
+ async function removeLocalFileIfInside(filePath, rootDir) {
64727
+ try {
64728
+ await localFileStatInsideRoot(filePath, rootDir);
64729
+ await fs7.rm(filePath, { force: true });
64730
+ } catch {
64803
64731
  }
64804
- dispose(err) {
64805
- if (this.disposed)
64806
- return;
64807
- this.disposed = true;
64808
- for (const pending of this.pending.values()) {
64809
- clearTimeout(pending.timer);
64810
- pending.reject(err);
64811
- }
64812
- this.pending.clear();
64732
+ }
64733
+ function sameFileIdentity(a, b) {
64734
+ return a.dev === b.dev && a.ino === b.ino;
64735
+ }
64736
+ function sameFile(a, b) {
64737
+ return sameFileIdentity(a, b) && a.size === b.size && a.mtimeMs === b.mtimeMs;
64738
+ }
64739
+ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
64740
+ let entries;
64741
+ try {
64742
+ entries = await fs7.readdir(rootDir, { withFileTypes: true });
64743
+ } catch {
64744
+ return;
64813
64745
  }
64814
- writeFrame(message) {
64746
+ const cutoff = Date.now() - ttlMs;
64747
+ await Promise.all(entries.map(async (entry) => {
64748
+ if (!entry.isDirectory())
64749
+ return;
64750
+ const fullPath = path9.join(rootDir, entry.name);
64815
64751
  try {
64816
- this.proc.stdin.write(`${JSON.stringify(message)}
64817
- `);
64752
+ if (preserveDirs?.has(path9.resolve(fullPath)))
64753
+ return;
64754
+ const stat2 = await fs7.lstat(fullPath);
64755
+ if (!stat2.isDirectory())
64756
+ return;
64757
+ if (stat2.mtimeMs < cutoff) {
64758
+ await fs7.rm(fullPath, { recursive: true, force: true });
64759
+ }
64818
64760
  } catch (err) {
64819
- this.killUnhealthy(err instanceof Error ? err : new Error(String(err)));
64761
+ log2?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
64820
64762
  }
64763
+ }));
64764
+ }
64765
+ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
64766
+ if (maxBytes <= 0)
64767
+ return;
64768
+ let entries;
64769
+ try {
64770
+ entries = await fs7.readdir(rootDir, { withFileTypes: true });
64771
+ } catch {
64772
+ return;
64821
64773
  }
64822
- killUnhealthy(err) {
64823
- this.dispose(err);
64824
- if (this.proc.exitCode === null && this.proc.signalCode === null) {
64825
- if (this.killProcess) {
64826
- this.killProcess(this.proc);
64827
- } else {
64828
- this.proc.kill("SIGTERM");
64829
- }
64774
+ const dirs = [];
64775
+ let total = 0;
64776
+ for (const entry of entries) {
64777
+ if (!entry.isDirectory())
64778
+ continue;
64779
+ const fullPath = path9.join(rootDir, entry.name);
64780
+ try {
64781
+ const stat2 = await fs7.lstat(fullPath);
64782
+ if (!stat2.isDirectory())
64783
+ continue;
64784
+ const size = await directorySize(fullPath);
64785
+ dirs.push({ path: fullPath, mtimeMs: stat2.mtimeMs, size });
64786
+ total += size;
64787
+ } catch (err) {
64788
+ log2?.warn?.(`agent-core: failed to inspect attachment cache dir ${fullPath}: ${String(err)}`);
64830
64789
  }
64831
64790
  }
64832
- ingest(chunk) {
64833
- this.buffer += chunk;
64834
- let newlineIndex = this.buffer.indexOf("\n");
64835
- while (newlineIndex >= 0) {
64836
- const line = this.buffer.slice(0, newlineIndex).trim();
64837
- this.buffer = this.buffer.slice(newlineIndex + 1);
64838
- if (line)
64839
- this.handleLine(line);
64840
- newlineIndex = this.buffer.indexOf("\n");
64791
+ if (total <= maxBytes)
64792
+ return;
64793
+ dirs.sort((a, b) => a.mtimeMs - b.mtimeMs);
64794
+ for (const dir of dirs) {
64795
+ if (total <= maxBytes)
64796
+ break;
64797
+ if (preserveDirs?.has(path9.resolve(dir.path)))
64798
+ continue;
64799
+ try {
64800
+ await fs7.rm(dir.path, { recursive: true, force: true });
64801
+ total -= dir.size;
64802
+ } catch (err) {
64803
+ log2?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
64841
64804
  }
64842
64805
  }
64843
- handleLine(line) {
64844
- let message;
64806
+ }
64807
+ async function directorySize(dirPath) {
64808
+ let total = 0;
64809
+ const entries = await fs7.readdir(dirPath, { withFileTypes: true });
64810
+ for (const entry of entries) {
64811
+ const fullPath = path9.join(dirPath, entry.name);
64812
+ let stat2;
64845
64813
  try {
64846
- message = JSON.parse(line);
64814
+ stat2 = await fs7.lstat(fullPath);
64847
64815
  } catch {
64848
- return;
64816
+ continue;
64849
64817
  }
64850
- if (isResponse(message)) {
64851
- const pending = this.pending.get(message.id);
64852
- if (!pending)
64853
- return;
64854
- this.pending.delete(message.id);
64855
- clearTimeout(pending.timer);
64856
- if (message.error) {
64857
- pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
64858
- } else {
64859
- pending.resolve(message.result);
64860
- }
64861
- return;
64818
+ if (stat2.isDirectory()) {
64819
+ total += await directorySize(fullPath);
64820
+ continue;
64862
64821
  }
64863
- if (isServerRequest(message)) {
64864
- this.answerServerRequest(message);
64822
+ if (!stat2.isFile())
64823
+ continue;
64824
+ total += stat2.size;
64825
+ }
64826
+ return total;
64827
+ }
64828
+ function activeDirsForRoot(rootDir) {
64829
+ const root = path9.resolve(rootDir);
64830
+ const dirs = /* @__PURE__ */ new Set();
64831
+ for (const dir of activeAttachmentDirs) {
64832
+ if (dir === root || dir.startsWith(`${root}${path9.sep}`)) {
64833
+ dirs.add(dir);
64834
+ }
64835
+ }
64836
+ return dirs;
64837
+ }
64838
+ async function downloadAttachmentToFile(url, filePath, maxBytes, timeoutMs, rootDir) {
64839
+ let parsed;
64840
+ try {
64841
+ parsed = new URL(url);
64842
+ } catch {
64843
+ throw new Error(`invalid attachment URL`);
64844
+ }
64845
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
64846
+ throw new Error(`refusing attachment URL with scheme ${parsed.protocol}`);
64847
+ }
64848
+ const controller = new AbortController();
64849
+ let timeout;
64850
+ if (timeoutMs > 0) {
64851
+ timeout = setTimeout(() => controller.abort(), timeoutMs);
64852
+ }
64853
+ try {
64854
+ const res = await fetch(url, { signal: controller.signal });
64855
+ if (!res.ok) {
64856
+ throw new Error(`${res.status} ${res.statusText}`);
64857
+ }
64858
+ const contentLength = parseContentLength(res.headers.get("content-length"));
64859
+ if (contentLength !== void 0 && contentLength > maxBytes) {
64860
+ throw new Error(`download would exceed ${formatBytes(maxBytes)} remaining turn limit`);
64861
+ }
64862
+ return await writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir);
64863
+ } catch (err) {
64864
+ if (isAbortError(err)) {
64865
+ throw new Error(`download timed out after ${timeoutMs}ms`);
64866
+ }
64867
+ throw err;
64868
+ } finally {
64869
+ if (timeout)
64870
+ clearTimeout(timeout);
64871
+ }
64872
+ }
64873
+ async function withTimeout(promise, timeoutMs, message) {
64874
+ if (timeoutMs <= 0)
64875
+ return promise;
64876
+ let timeout;
64877
+ try {
64878
+ return await Promise.race([
64879
+ promise,
64880
+ new Promise((_, reject) => {
64881
+ timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
64882
+ })
64883
+ ]);
64884
+ } finally {
64885
+ if (timeout)
64886
+ clearTimeout(timeout);
64887
+ }
64888
+ }
64889
+ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
64890
+ if (maxBytes <= 0) {
64891
+ throw new Error("download would exceed turn limit");
64892
+ }
64893
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
64894
+ const { file, openedStat } = await openLocalTempFileInsideRoot(tmpPath, rootDir);
64895
+ let written = 0;
64896
+ let completed = false;
64897
+ let fileClosed = false;
64898
+ let writtenStat = openedStat;
64899
+ const closeFile = async () => {
64900
+ if (fileClosed)
64865
64901
  return;
64902
+ await file.close();
64903
+ fileClosed = true;
64904
+ };
64905
+ try {
64906
+ if (!res.body) {
64907
+ const buffer = Buffer.from(await res.arrayBuffer());
64908
+ if (buffer.byteLength > maxBytes) {
64909
+ throw new Error(`download exceeded ${formatBytes(maxBytes)} remaining turn limit`);
64910
+ }
64911
+ await file.write(buffer);
64912
+ written = buffer.byteLength;
64913
+ } else {
64914
+ const reader = res.body.getReader();
64915
+ while (true) {
64916
+ const { done, value } = await reader.read();
64917
+ if (done)
64918
+ break;
64919
+ const chunk = Buffer.from(value);
64920
+ written += chunk.byteLength;
64921
+ if (written > maxBytes) {
64922
+ throw new Error(`download exceeded ${formatBytes(maxBytes)} remaining turn limit`);
64923
+ }
64924
+ await file.write(chunk);
64925
+ }
64866
64926
  }
64867
- if (isNotification(message)) {
64868
- this.onNotification?.(message.method, message.params);
64927
+ writtenStat = await file.stat();
64928
+ await closeFile();
64929
+ await localDirectoryStatInsideRoot(path9.dirname(filePath), rootDir);
64930
+ await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
64931
+ await fs7.rename(tmpPath, filePath);
64932
+ completed = true;
64933
+ return written;
64934
+ } finally {
64935
+ if (!fileClosed) {
64936
+ try {
64937
+ await closeFile();
64938
+ } catch {
64939
+ }
64940
+ }
64941
+ if (!completed) {
64942
+ await removeLocalFileIfInside(tmpPath, rootDir);
64869
64943
  }
64870
64944
  }
64871
- answerServerRequest(request3) {
64872
- let answer;
64873
- try {
64874
- answer = this.onServerRequest?.(request3.method, request3.params);
64875
- } catch (err) {
64876
- this.writeFrame({
64877
- jsonrpc: "2.0",
64878
- id: request3.id,
64879
- error: { code: -32603, message: `server request handler failed: ${String(err)}` }
64880
- });
64881
- return;
64882
- }
64883
- if (answer !== void 0) {
64884
- this.writeFrame({
64885
- jsonrpc: "2.0",
64886
- id: request3.id,
64887
- result: answer.result === void 0 ? null : answer.result
64888
- });
64889
- return;
64890
- }
64891
- this.writeFrame({
64892
- jsonrpc: "2.0",
64893
- id: request3.id,
64894
- error: { code: -32601, message: `unsupported server request: ${request3.method}` }
64895
- });
64945
+ }
64946
+ function localFileName(attachmentId, fileName, mimeType) {
64947
+ const safeName = sanitizePathSegment(path9.basename(fileName || attachmentId));
64948
+ const ext = path9.extname(safeName) || extensionForMime(mimeType);
64949
+ const stem = path9.basename(safeName, path9.extname(safeName)) || attachmentId;
64950
+ return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
64951
+ }
64952
+ function extensionForMime(mimeType) {
64953
+ switch (mimeType.toLowerCase()) {
64954
+ case "image/jpeg":
64955
+ case "image/jpg":
64956
+ return ".jpg";
64957
+ case "image/webp":
64958
+ return ".webp";
64959
+ case "image/gif":
64960
+ return ".gif";
64961
+ case "image/png":
64962
+ default:
64963
+ return ".png";
64964
+ }
64965
+ }
64966
+ function sanitizePathSegment(value) {
64967
+ const safe = value.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
64968
+ if (!safe || /^\.+$/.test(safe))
64969
+ return "attachment";
64970
+ return safe;
64971
+ }
64972
+ async function downloadedFileMatchesImageMime(filePath, mimeType, rootDir) {
64973
+ const file = await openLocalFileInsideRoot(filePath, rootDir);
64974
+ try {
64975
+ const buffer = Buffer.alloc(16);
64976
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
64977
+ return imageHeaderMatches(buffer.subarray(0, bytesRead), mimeType);
64978
+ } finally {
64979
+ await file.close();
64980
+ }
64981
+ }
64982
+ function imageHeaderMatches(bytes, mimeType) {
64983
+ switch (mimeType.toLowerCase()) {
64984
+ case "image/png":
64985
+ return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10;
64986
+ case "image/jpeg":
64987
+ case "image/jpg":
64988
+ return bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
64989
+ case "image/gif":
64990
+ return bytes.length >= 6 && (bytes.subarray(0, 6).toString("ascii") === "GIF87a" || bytes.subarray(0, 6).toString("ascii") === "GIF89a");
64991
+ case "image/webp":
64992
+ return bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
64993
+ default:
64994
+ return false;
64896
64995
  }
64897
- };
64898
- function isResponse(m) {
64899
- return !!m && typeof m === "object" && "id" in m && ("result" in m || "error" in m);
64900
64996
  }
64901
- function isServerRequest(m) {
64902
- return !!m && typeof m === "object" && "method" in m && "id" in m;
64997
+ function isAbortError(err) {
64998
+ return err instanceof DOMException && err.name === "AbortError";
64903
64999
  }
64904
- function isNotification(m) {
64905
- return !!m && typeof m === "object" && "method" in m && !("id" in m);
65000
+ function sanitizeMeta2(value) {
65001
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
65002
+ }
65003
+ function parseContentLength(value) {
65004
+ if (!value)
65005
+ return void 0;
65006
+ const n = Number(value);
65007
+ if (!Number.isFinite(n) || n < 0)
65008
+ return void 0;
65009
+ return n;
65010
+ }
65011
+
65012
+ // ts/codex-agent/dist/app-server-process.js
65013
+ import { execSync as execSync2 } from "node:child_process";
65014
+ import * as fs8 from "node:fs";
65015
+ var IS_WIN32 = process.platform === "win32";
65016
+ function quoteWin32Arg(arg) {
65017
+ if (!/[\s"&|^<>()]/.test(arg))
65018
+ return arg;
65019
+ return `"${arg.replace(/"/g, '""')}"`;
65020
+ }
65021
+ function killWin32Tree(pid) {
65022
+ try {
65023
+ execSync2(`taskkill /T /F /PID ${pid}`, { windowsHide: true, stdio: "ignore" });
65024
+ return true;
65025
+ } catch {
65026
+ return false;
65027
+ }
65028
+ }
65029
+ function ensureGitRepo(workingDirectory) {
65030
+ fs8.mkdirSync(workingDirectory, { recursive: true });
65031
+ try {
65032
+ execSync2("git rev-parse --is-inside-work-tree", { cwd: workingDirectory, stdio: "pipe" });
65033
+ ensureLocalAttachmentGitExclude(workingDirectory);
65034
+ return;
65035
+ } catch {
65036
+ }
65037
+ const env = {
65038
+ ...process.env,
65039
+ GIT_AUTHOR_NAME: "parall-codex-agent",
65040
+ GIT_AUTHOR_EMAIL: "agent@parall.local",
65041
+ GIT_COMMITTER_NAME: "parall-codex-agent",
65042
+ GIT_COMMITTER_EMAIL: "agent@parall.local"
65043
+ };
65044
+ try {
65045
+ execSync2("git init", { cwd: workingDirectory, stdio: "pipe", env });
65046
+ execSync2("git commit --allow-empty -m init", { cwd: workingDirectory, stdio: "pipe", env });
65047
+ ensureLocalAttachmentGitExclude(workingDirectory);
65048
+ } catch {
65049
+ }
64906
65050
  }
64907
65051
 
64908
65052
  // ts/codex-agent/dist/instructions-refresh.js
65053
+ import { createHash } from "node:crypto";
64909
65054
  function sha256Hex(text) {
64910
65055
  return createHash("sha256").update(text, "utf8").digest("hex");
64911
65056
  }
@@ -64994,14 +65139,14 @@ var MainThreadInstructionsRefresher = class {
64994
65139
  return "refreshed";
64995
65140
  } catch (err) {
64996
65141
  if (err instanceof CompactionStalledError) {
64997
- log2?.warn?.(`platform instructions refresh stalled (${errToString(err)}); bouncing the subprocess before the next turn`);
65142
+ log2?.warn?.(`platform instructions refresh stalled (${errToString2(err)}); bouncing the subprocess before the next turn`);
64998
65143
  return "stalled";
64999
65144
  }
65000
65145
  if (err instanceof JsonRpcError && err.code === JSON_RPC_METHOD_NOT_FOUND) {
65001
65146
  log2?.warn?.("thread/compact/start not supported by this codex CLI; the persisted thread keeps its previous platform instructions until it is replaced or the CLI is upgraded (tools still refresh live via the capability shim dir)");
65002
65147
  return "unsupported";
65003
65148
  }
65004
- log2?.warn?.(`platform instructions refresh did not complete (will retry next dispatch; the resumed configuration already carries the new value): ${errToString(err)}`);
65149
+ log2?.warn?.(`platform instructions refresh did not complete (will retry next dispatch; the resumed configuration already carries the new value): ${errToString2(err)}`);
65005
65150
  return "failed";
65006
65151
  }
65007
65152
  }
@@ -65159,7 +65304,7 @@ function turnIdOf(params) {
65159
65304
  const turn = params?.turn;
65160
65305
  return typeof turn?.id === "string" ? turn.id : void 0;
65161
65306
  }
65162
- function errToString(err) {
65307
+ function errToString2(err) {
65163
65308
  if (err instanceof Error)
65164
65309
  return err.message;
65165
65310
  return String(err);
@@ -65225,12 +65370,12 @@ async function runCodexCompact(host, { sessionKey, signal, log: log2 }) {
65225
65370
  } catch (err) {
65226
65371
  if (err instanceof CompactionStalledError) {
65227
65372
  stalled = true;
65228
- return { status: "timeout", detail: errToString2(err) };
65373
+ return { status: "timeout", detail: errToString3(err) };
65229
65374
  }
65230
65375
  if (err instanceof JsonRpcError && err.code === JSON_RPC_METHOD_NOT_FOUND) {
65231
- return { status: "unsupported", detail: errToString2(err) };
65376
+ return { status: "unsupported", detail: errToString3(err) };
65232
65377
  }
65233
- return { status: "failed", detail: errToString2(err) };
65378
+ return { status: "failed", detail: errToString3(err) };
65234
65379
  }
65235
65380
  });
65236
65381
  } finally {
@@ -65239,7 +65384,7 @@ async function runCodexCompact(host, { sessionKey, signal, log: log2 }) {
65239
65384
  }
65240
65385
  }
65241
65386
  }
65242
- function errToString2(err) {
65387
+ function errToString3(err) {
65243
65388
  if (err instanceof Error)
65244
65389
  return err.message;
65245
65390
  return String(err);
@@ -65443,15 +65588,19 @@ var EventMapper = class {
65443
65588
  }
65444
65589
  const durationMs = this.resolveDuration(callId, now, item.durationMs);
65445
65590
  const result = item.result;
65446
- const output = result == null ? "" : typeof result === "string" ? result : JSON.stringify(result);
65447
- const success = item.isSuccess !== false;
65591
+ const resultOutput = result == null ? "" : typeof result === "string" ? result : JSON.stringify(result);
65592
+ const error = item.error;
65593
+ const failed = item.status === "failed" || error != null;
65594
+ const message = asString(error?.message);
65595
+ const failure = failed ? message || "MCP tool call failed" : void 0;
65596
+ const output = message ? [resultOutput, message].filter(Boolean).join("\n") : resultOutput || failure || "";
65448
65597
  return [
65449
65598
  {
65450
65599
  type: "tool_result",
65451
65600
  callId,
65452
65601
  toolName,
65453
65602
  output,
65454
- ...success ? {} : { error: output || "MCP tool call failed" },
65603
+ ...failure ? { error: failure } : {},
65455
65604
  ...durationMs !== void 0 ? { durationMs } : {}
65456
65605
  }
65457
65606
  ];
@@ -65471,12 +65620,15 @@ var EventMapper = class {
65471
65620
  ];
65472
65621
  }
65473
65622
  const durationMs = this.resolveDuration(callId, now, void 0);
65623
+ const status = asString(item.status);
65624
+ const failure = status === "failed" || status === "declined" ? `File change ${status}` : void 0;
65474
65625
  return [
65475
65626
  {
65476
65627
  type: "tool_result",
65477
65628
  callId,
65478
65629
  toolName: "patch",
65479
- output: "",
65630
+ output: failure ?? "",
65631
+ ...failure ? { error: failure } : {},
65480
65632
  ...durationMs !== void 0 ? { durationMs } : {}
65481
65633
  }
65482
65634
  ];
@@ -65647,9 +65799,59 @@ var TurnSink = class {
65647
65799
  noteActivity;
65648
65800
  mapper = new EventMapper();
65649
65801
  queue = new AsyncQueue();
65802
+ pending = [];
65803
+ inputWaiter;
65804
+ input;
65805
+ completedTurnId;
65650
65806
  constructor(noteActivity) {
65651
65807
  this.noteActivity = noteActivity;
65652
65808
  }
65809
+ /** Buffer pre-response traffic; only the input's exact turn may drain it. */
65810
+ receive(method, params) {
65811
+ if (this.isClosed || this.completedTurnId)
65812
+ return;
65813
+ if (this.input?.observed)
65814
+ this.inputWaiter?.();
65815
+ if (!this.input?.turnId) {
65816
+ this.pending.push({ method, params });
65817
+ return;
65818
+ }
65819
+ this.flushPending();
65820
+ this.mapNotification(method, params);
65821
+ }
65822
+ /** An uncertain RPC response must not cut off later native input evidence. */
65823
+ async waitForInputOrClose() {
65824
+ if (this.input?.observed || this.isClosed)
65825
+ return;
65826
+ await new Promise((resolve4) => {
65827
+ this.inputWaiter = resolve4;
65828
+ });
65829
+ this.inputWaiter = void 0;
65830
+ }
65831
+ flushPending() {
65832
+ if (!this.input?.turnId)
65833
+ return;
65834
+ const pending = this.pending;
65835
+ this.pending = [];
65836
+ for (const notification of pending) {
65837
+ this.mapNotification(notification.method, notification.params);
65838
+ }
65839
+ }
65840
+ mapNotification(method, params) {
65841
+ if (this.completedTurnId || this.isClosed)
65842
+ return;
65843
+ const turnId = extractTurnId(params);
65844
+ if (!turnId || turnId !== this.input?.turnId)
65845
+ return;
65846
+ this.touchActivity();
65847
+ for (const event of this.mapper.map(method, params)) {
65848
+ this.push({ kind: "runtime", event });
65849
+ }
65850
+ if (method === "turn/completed") {
65851
+ this.completedTurnId = turnId;
65852
+ this.push({ kind: "turn_end", threadId: this.input.threadId });
65853
+ }
65854
+ }
65653
65855
  touchActivity() {
65654
65856
  this.noteActivity?.();
65655
65857
  }
@@ -65661,7 +65863,9 @@ var TurnSink = class {
65661
65863
  return result.done ? { kind: "turn_end" } : result.value;
65662
65864
  }
65663
65865
  close() {
65866
+ this.pending = [];
65664
65867
  this.queue.close();
65868
+ this.inputWaiter?.();
65665
65869
  }
65666
65870
  /** True once close() ran — the sink's terminal state (queued envelopes may
65667
65871
  * still drain via next()). */
@@ -65716,6 +65920,65 @@ var CodexRuntimeTurn = class extends RuntimeTurnBase {
65716
65920
  }
65717
65921
  };
65718
65922
 
65923
+ // ts/codex-agent/dist/runtime-observations.js
65924
+ function codexObservation(method, params) {
65925
+ const threadId = observationField(extractThreadIdFromNotification(params));
65926
+ if (!threadId || !params || typeof params !== "object")
65927
+ return;
65928
+ const p = params;
65929
+ const native = { thread_id: threadId };
65930
+ let event;
65931
+ let status = "unknown";
65932
+ let waiting_on;
65933
+ switch (method) {
65934
+ case "turn/started":
65935
+ case "turn/completed": {
65936
+ native.turn_id = observationField(extractTurnId(params));
65937
+ if (!native.turn_id)
65938
+ return;
65939
+ event = method === "turn/started" ? "turn_started" : "turn_completed";
65940
+ native.status = observationField(p.turn?.status);
65941
+ status = method === "turn/started" ? "running" : p.turn?.status === "completed" ? "completed" : p.turn?.status === "failed" ? "failed" : p.turn?.status === "interrupted" ? "interrupted" : "unknown";
65942
+ break;
65943
+ }
65944
+ case "thread/status/changed": {
65945
+ event = "thread_status";
65946
+ native.status = observationField(p.status?.type);
65947
+ status = p.status?.type === "active" ? "running" : p.status?.type === "idle" ? "idle" : p.status?.type === "notLoaded" ? "not_loaded" : p.status?.type === "systemError" ? "system_error" : "unknown";
65948
+ if (p.status?.type === "active" && Array.isArray(p.status.activeFlags)) {
65949
+ waiting_on = [];
65950
+ if (p.status.activeFlags.includes("waitingOnApproval"))
65951
+ waiting_on.push("approval");
65952
+ if (p.status.activeFlags.includes("waitingOnUserInput"))
65953
+ waiting_on.push("user_input");
65954
+ }
65955
+ break;
65956
+ }
65957
+ case "hook/started":
65958
+ case "hook/completed": {
65959
+ event = method === "hook/started" ? "hook_started" : "hook_completed";
65960
+ native.turn_id = observationField(p.turnId);
65961
+ native.hook_id = observationField(p.run?.id);
65962
+ native.hook_event = observationField(p.run?.eventName);
65963
+ native.hook_scope = observationField(p.run?.scope);
65964
+ native.status = observationField(p.run?.status);
65965
+ const statuses = ["running", "completed", "failed", "blocked", "stopped"];
65966
+ status = statuses.find((s) => s === p.run?.status) ?? "unknown";
65967
+ break;
65968
+ }
65969
+ default:
65970
+ return;
65971
+ }
65972
+ return runtimeObservation(threadId, {
65973
+ runtime: "codex",
65974
+ source: "app_server",
65975
+ event,
65976
+ status,
65977
+ native,
65978
+ ...waiting_on?.length ? { waiting_on } : {}
65979
+ });
65980
+ }
65981
+
65719
65982
  // ts/codex-agent/dist/foreign-threads.js
65720
65983
  var ForeignThreadRegistry = class {
65721
65984
  host;
@@ -65769,8 +66032,22 @@ var ForeignThreadRegistry = class {
65769
66032
  thread.turn.touch();
65770
66033
  else
65771
66034
  this.openTurn(thread);
66035
+ const observation2 = codexObservation(method, params);
66036
+ if (observation2)
66037
+ thread.turn?.sink.push({ kind: "runtime", event: observation2 });
65772
66038
  return true;
65773
66039
  }
66040
+ const observation = codexObservation(method, params);
66041
+ if (observation) {
66042
+ if (thread.turn)
66043
+ thread.turn.sink.push({ kind: "runtime", event: observation });
66044
+ else
66045
+ this.host.activity.emit({
66046
+ kind: "observation",
66047
+ sessionKey: thread.sessionKey,
66048
+ event: observation
66049
+ });
66050
+ }
65774
66051
  if (!thread.turn) {
65775
66052
  if (method !== "turn/completed" && !method.startsWith("item/"))
65776
66053
  return true;
@@ -65849,83 +66126,174 @@ var ForeignThreadRegistry = class {
65849
66126
  }
65850
66127
  };
65851
66128
 
65852
- // ts/codex-agent/dist/injection-registry.js
65853
- var CodexInjectionRegistry = class {
65854
- sessions = /* @__PURE__ */ new Map();
65855
- /** Record a successful steer. `deliveryKey` may join several WorkItem ids with ','. */
65856
- register(sessionKey, deliveryKey) {
65857
- let entries = this.sessions.get(sessionKey);
65858
- if (!entries) {
65859
- entries = /* @__PURE__ */ new Map();
65860
- this.sessions.set(sessionKey, entries);
66129
+ // ts/codex-agent/dist/dispatch-notifications.js
66130
+ var CodexNotificationRouter = class {
66131
+ lastUnroutedNotificationWarnAt = 0;
66132
+ route(host, method, params) {
66133
+ for (const tap of host.notificationTaps) {
66134
+ try {
66135
+ tap(method, params);
66136
+ } catch (err) {
66137
+ host.log?.warn?.(`notification tap threw: ${errToString4(err)}`);
66138
+ }
66139
+ }
66140
+ const threadId = extractThreadIdFromNotification(params);
66141
+ if (!threadId) {
66142
+ if (method === "error") {
66143
+ const msg = params?.message ?? "Codex app-server error";
66144
+ for (const sink2 of host.activeTurns.values()) {
66145
+ sink2.push({ kind: "error", message: String(msg) });
66146
+ }
66147
+ }
66148
+ return;
65861
66149
  }
65862
- for (const id of splitDeliveryKey(deliveryKey)) {
65863
- if (!entries.has(id))
65864
- entries.set(id, { settled: false, drained: false });
66150
+ const sink = host.activeTurns.get(threadId);
66151
+ const observation = codexObservation(method, params);
66152
+ if (observation) {
66153
+ if (sink && !sink.isClosed && !sink.completedTurnId) {
66154
+ sink.push({ kind: "runtime", event: observation });
66155
+ } else {
66156
+ const sessionKey = host.sessionManager.getSessionKey(threadId);
66157
+ if (sessionKey)
66158
+ host.activity.emit({ kind: "observation", sessionKey, event: observation });
66159
+ }
65865
66160
  }
65866
- }
65867
- /** The buffered copies behind these WorkItems drained (group dispatch or discard). */
65868
- markDrained(sessionKey, deliveryKey) {
65869
- const entries = this.sessions.get(sessionKey);
65870
- if (!entries)
66161
+ if (!sink) {
66162
+ if (host.reconcilingThreadIds.has(threadId))
66163
+ return;
66164
+ if (host.foreignThreads.route(method, params, threadId))
66165
+ return;
66166
+ if (observation && host.sessionManager.getSessionKey(threadId))
66167
+ return;
66168
+ const now = Date.now();
66169
+ if (now - this.lastUnroutedNotificationWarnAt > 1e4) {
66170
+ this.lastUnroutedNotificationWarnAt = now;
66171
+ host.log?.warn?.(`dropping notification "${method}" for unknown thread ${threadId}`);
66172
+ }
65871
66173
  return;
65872
- for (const id of splitDeliveryKey(deliveryKey)) {
65873
- const entry = entries.get(id);
65874
- if (!entry)
65875
- continue;
65876
- entry.drained = true;
65877
- if (entry.settled)
65878
- entries.delete(id);
65879
66174
  }
65880
- if (entries.size === 0)
65881
- this.sessions.delete(sessionKey);
66175
+ host.inputs.observe(method, params);
66176
+ sink.receive(method, params);
66177
+ if (sink.completedTurnId) {
66178
+ host.inputs.settleTurn(threadId, sink.completedTurnId);
66179
+ host.activeTurnIds.delete(threadId);
66180
+ } else if (sink.input?.turnId) {
66181
+ host.activeTurnIds.set(threadId, sink.input.turnId);
66182
+ }
66183
+ }
66184
+ };
66185
+ function errToString4(err) {
66186
+ return err instanceof Error ? err.message : String(err);
66187
+ }
66188
+
66189
+ // ts/codex-agent/dist/input-receipts.js
66190
+ import { randomUUID as randomUUID6 } from "node:crypto";
66191
+ var CodexInputReceipts = class {
66192
+ log;
66193
+ inputs = /* @__PURE__ */ new Map();
66194
+ constructor(log2) {
66195
+ this.log = log2;
65882
66196
  }
65883
- /** The turn every injection of this session was steered into has ended. */
65884
- settleAll(sessionKey) {
65885
- const entries = this.sessions.get(sessionKey);
65886
- if (!entries)
66197
+ register(sessionKey, threadId, lifecycle, turnId) {
66198
+ const input = {
66199
+ clientId: randomUUID6(),
66200
+ sessionKey,
66201
+ threadId,
66202
+ turnId,
66203
+ lifecycle,
66204
+ injected: turnId !== void 0,
66205
+ undrained: new Set(turnId ? lifecycle?.dispatchEventIds : []),
66206
+ ended: false
66207
+ };
66208
+ this.inputs.set(input.clientId, input);
66209
+ return input;
66210
+ }
66211
+ /** Only an exact native userMessage item can report input application. */
66212
+ observe(method, params) {
66213
+ if (method !== "item/started" && method !== "item/completed")
66214
+ return;
66215
+ const p = params;
66216
+ const item = p?.item;
66217
+ if (item?.type !== "userMessage" || typeof item.clientId !== "string")
66218
+ return;
66219
+ const input = this.inputs.get(item.clientId);
66220
+ const threadId = extractThreadIdFromNotification(params);
66221
+ const turnId = extractTurnId(params);
66222
+ if (!input || input.ended || !turnId || input.threadId !== threadId)
66223
+ return;
66224
+ if (input.turnId && input.turnId !== turnId)
65887
66225
  return;
65888
- for (const [id, entry] of entries) {
65889
- entry.settled = true;
65890
- if (entry.drained)
65891
- entries.delete(id);
66226
+ input.turnId = turnId;
66227
+ const state = method === "item/completed" ? "completed" : "started";
66228
+ if (input.observed === "completed" || input.observed === state)
66229
+ return input;
66230
+ input.observed = state;
66231
+ try {
66232
+ void input.lifecycle?.update(state).catch((err) => {
66233
+ this.log?.error(`Codex input receipt callback failed: ${String(err)}`);
66234
+ });
66235
+ } catch (err) {
66236
+ this.log?.error(`Codex input receipt callback failed: ${String(err)}`);
65892
66237
  }
65893
- if (entries.size === 0)
65894
- this.sessions.delete(sessionKey);
66238
+ return input;
65895
66239
  }
65896
- /** An injection whose buffered copy has not drained yet (bookkeeping owed). */
65897
- hasPending(sessionKey) {
65898
- const entries = this.sessions.get(sessionKey);
65899
- if (!entries)
65900
- return false;
65901
- for (const entry of entries.values()) {
65902
- if (!entry.drained)
65903
- return true;
66240
+ bind(input, turnId) {
66241
+ if (input.turnId && input.turnId !== turnId) {
66242
+ throw new Error("Codex turn/start response disagrees with the native input turn");
65904
66243
  }
65905
- return false;
66244
+ input.turnId = turnId;
65906
66245
  }
65907
- /** An injection whose turn is still running (the only state that may defer a complete). */
65908
- hasUnsettled(sessionKey) {
65909
- const entries = this.sessions.get(sessionKey);
65910
- if (!entries)
65911
- return false;
65912
- for (const entry of entries.values()) {
65913
- if (!entry.settled)
65914
- return true;
66246
+ settleTurn(threadId, turnId) {
66247
+ for (const input of this.inputs.values()) {
66248
+ if (input.threadId === threadId && input.turnId === turnId) {
66249
+ input.ended = true;
66250
+ this.removeIfDrained(input);
66251
+ }
65915
66252
  }
65916
- return false;
65917
66253
  }
65918
- /** Drop every entry (turn aborted / subprocess gone): nothing is owed anymore. */
66254
+ /** A local dispatch ending is not a positive or negative input receipt. */
66255
+ finish(input) {
66256
+ if (input.turnId)
66257
+ this.settleTurn(input.threadId, input.turnId);
66258
+ this.inputs.delete(input.clientId);
66259
+ }
66260
+ forget(input) {
66261
+ this.inputs.delete(input.clientId);
66262
+ }
66263
+ markDrained(sessionKey, deliveryKey) {
66264
+ const ids = deliveryKey.split(",");
66265
+ for (const input of this.inputs.values()) {
66266
+ if (input.sessionKey !== sessionKey || !input.injected)
66267
+ continue;
66268
+ for (const id of ids)
66269
+ input.undrained.delete(id);
66270
+ this.removeIfDrained(input);
66271
+ }
66272
+ }
66273
+ hasPending(sessionKey) {
66274
+ return [...this.inputs.values()].some((input) => input.sessionKey === sessionKey && input.undrained.size > 0);
66275
+ }
66276
+ hasUnsettled(sessionKey) {
66277
+ return [...this.inputs.values()].some((input) => input.sessionKey === sessionKey && input.injected && !input.ended);
66278
+ }
65919
66279
  clear(sessionKey) {
65920
- if (sessionKey === void 0) {
65921
- this.sessions.clear();
65922
- return;
66280
+ for (const input of this.inputs.values()) {
66281
+ if (sessionKey === void 0 || input.sessionKey === sessionKey) {
66282
+ this.inputs.delete(input.clientId);
66283
+ }
65923
66284
  }
65924
- this.sessions.delete(sessionKey);
66285
+ }
66286
+ removeIfDrained(input) {
66287
+ if (input.ended && input.undrained.size === 0)
66288
+ this.inputs.delete(input.clientId);
65925
66289
  }
65926
66290
  };
65927
- function splitDeliveryKey(deliveryKey) {
65928
- return deliveryKey.split(",").map((id) => id.trim()).filter((id) => id.length > 0);
66291
+ function requireCodexInputReceipts(initialize) {
66292
+ const userAgent = initialize?.userAgent;
66293
+ const version = typeof userAgent === "string" ? /^\S+\/(\d+)\.(\d+)\.(\d+)\s/.exec(userAgent) : null;
66294
+ if (!version || Number(version[1]) === 0 && Number(version[2]) < 151) {
66295
+ throw new Error("Codex input receipts require a recognized stable Codex CLI >= 0.151.0; upgrade the CLI before sending business input");
66296
+ }
65929
66297
  }
65930
66298
 
65931
66299
  // ts/codex-agent/dist/server-requests.js
@@ -65963,13 +66331,15 @@ function buildThreadConfigOverrides({ reasoningEffort, capabilityBinDir: capabil
65963
66331
  // ts/codex-agent/dist/dispatch.js
65964
66332
  var CodexAppServerAdapter = class {
65965
66333
  opts;
66334
+ inputLifecycleMode = "explicit";
66335
+ inputSettlementMode = "receipt";
65966
66336
  client = null;
65967
66337
  proc = null;
65968
66338
  initialized = false;
65969
66339
  startPromise = null;
65970
66340
  activeTurns = /* @__PURE__ */ new Map();
65971
66341
  activeTurnIds = /* @__PURE__ */ new Map();
65972
- injections = new CodexInjectionRegistry();
66342
+ injections;
65973
66343
  resumedThreadIds = /* @__PURE__ */ new Set();
65974
66344
  /** Threads whose reconcile compaction is in flight — tap-only traffic. */
65975
66345
  reconcilingThreadIds = /* @__PURE__ */ new Set();
@@ -65986,7 +66356,7 @@ var CodexAppServerAdapter = class {
65986
66356
  notificationTaps = /* @__PURE__ */ new Set();
65987
66357
  instructionsRefresher;
65988
66358
  stopping = false;
65989
- lastUnroutedNotificationWarnAt = 0;
66359
+ notifications = new CodexNotificationRouter();
65990
66360
  /** Subagent threads and their runtime-initiated turns (foreign-threads.ts). */
65991
66361
  foreignThreads;
65992
66362
  activity;
@@ -66009,6 +66379,7 @@ var CodexAppServerAdapter = class {
66009
66379
  }
66010
66380
  constructor(opts) {
66011
66381
  this.opts = opts;
66382
+ this.injections = new CodexInputReceipts(opts.log);
66012
66383
  this.instructionsRefresher = new MainThreadInstructionsRefresher({
66013
66384
  sessionManager: opts.sessionManager,
66014
66385
  log: opts.log,
@@ -66024,7 +66395,7 @@ var CodexAppServerAdapter = class {
66024
66395
  afterTurnClosed: () => {
66025
66396
  if (!this.restartRequested)
66026
66397
  return;
66027
- void this.applyPendingRestart().catch((err) => this.opts.log?.warn?.(`deferred restart failed: ${errToString3(err)}`));
66398
+ void this.applyPendingRestart().catch((err) => this.opts.log?.warn?.(`deferred restart failed: ${errToString5(err)}`));
66028
66399
  }
66029
66400
  });
66030
66401
  }
@@ -66074,30 +66445,35 @@ var CodexAppServerAdapter = class {
66074
66445
  const turnId = this.activeTurnIds.get(threadId);
66075
66446
  if (!turnId)
66076
66447
  return false;
66448
+ const input = this.injections.register(sessionKey, threadId, inputLifecycle, turnId);
66077
66449
  try {
66078
66450
  await client.sendRequest("turn/steer", {
66079
66451
  threadId,
66080
66452
  expectedTurnId: turnId,
66453
+ clientUserMessageId: input.clientId,
66081
66454
  input: buildTurnInput(body, [])
66082
66455
  });
66083
- this.injections.register(sessionKey, inputLifecycle.deliveryKey);
66084
66456
  return true;
66085
66457
  } catch (err) {
66086
- this.opts.log?.warn?.(`turn/steer failed: ${errToString3(err)}`);
66087
- return false;
66458
+ this.opts.log?.warn?.(`turn/steer failed: ${errToString5(err)}`);
66459
+ if (err instanceof JsonRpcError && !input.observed) {
66460
+ this.injections.forget(input);
66461
+ return false;
66462
+ }
66463
+ return true;
66088
66464
  }
66089
66465
  }
66090
66466
  abortDispatch(sessionKey) {
66091
66467
  this.injections.clear(sessionKey);
66092
- const threadId = this.opts.sessionManager.getThreadId(sessionKey);
66093
- if (!threadId)
66468
+ const active = [...this.activeTurns].find(([id, candidate]) => candidate.input?.sessionKey === sessionKey || this.opts.sessionManager.getThreadId(sessionKey) === id);
66469
+ if (!active)
66094
66470
  return;
66095
- const sink = this.activeTurns.get(threadId);
66471
+ const [threadId, sink] = active;
66096
66472
  if (!sink || sink.isClosed)
66097
66473
  return;
66098
66474
  const turnId = this.activeTurnIds.get(threadId);
66099
66475
  if (turnId && this.client && !this.client.isDisposed()) {
66100
- this.client.sendRequest("turn/interrupt", { threadId, turnId }).catch((err) => this.opts.log?.warn?.(`turn/interrupt failed: ${errToString3(err)}`));
66476
+ this.client.sendRequest("turn/interrupt", { threadId, turnId }).catch((err) => this.opts.log?.warn?.(`turn/interrupt failed: ${errToString5(err)}`));
66101
66477
  }
66102
66478
  sink.push({ kind: "error", message: "dispatch inactivity deadline exceeded" });
66103
66479
  sink.close();
@@ -66218,7 +66594,7 @@ var CodexAppServerAdapter = class {
66218
66594
  }
66219
66595
  const sink = new TurnSink(noteActivity);
66220
66596
  this.setActiveTurn(threadId, sink, log2);
66221
- const groupKey = randomUUID4();
66597
+ const groupKey = randomUUID7();
66222
66598
  let sawTurnEnd = false;
66223
66599
  let releasePreparedAttachments = () => {
66224
66600
  };
@@ -66234,26 +66610,27 @@ var CodexAppServerAdapter = class {
66234
66610
  preparedImages = prepared.attachments.images;
66235
66611
  releasePreparedAttachments = pinLocalAttachmentPaths(preparedImages);
66236
66612
  } catch (err) {
66237
- log2?.warn?.(`failed to prepare local attachments: ${errToString3(err)}`);
66613
+ log2?.warn?.(`failed to prepare local attachments: ${errToString5(err)}`);
66238
66614
  }
66239
66615
  const turnInput = buildTurnInput(preparedBody, preparedImages);
66240
- const startTurn = (targetThreadId) => {
66241
- const turnParams = {
66242
- threadId: targetThreadId,
66243
- input: turnInput
66244
- };
66245
- if (this.opts.model)
66246
- turnParams.model = this.opts.model;
66247
- if (this.opts.reasoningEffort)
66248
- turnParams.effort = this.opts.reasoningEffort;
66249
- return client.sendRequest("turn/start", turnParams);
66250
- };
66251
- let turnStartResult;
66616
+ const startTurn = (targetThreadId) => startCodexInput({
66617
+ client,
66618
+ receipts: this.injections,
66619
+ sink,
66620
+ sessionKey,
66621
+ threadId: targetThreadId,
66622
+ inputLifecycle,
66623
+ input: turnInput,
66624
+ model: this.opts.model,
66625
+ effort: this.opts.reasoningEffort,
66626
+ log: log2
66627
+ });
66628
+ let turnId;
66252
66629
  try {
66253
- turnStartResult = await startTurn(threadId);
66630
+ turnId = await startTurn(threadId);
66254
66631
  } catch (err) {
66255
- const message = errToString3(err);
66256
- if (!isMainSession) {
66632
+ const message = errToString5(err);
66633
+ if (!isMainSession || !(err instanceof JsonRpcError)) {
66257
66634
  yield {
66258
66635
  type: "runtime_session",
66259
66636
  runtimeSessionId: threadId,
@@ -66291,13 +66668,13 @@ var CodexAppServerAdapter = class {
66291
66668
  };
66292
66669
  yield {
66293
66670
  type: "error",
66294
- message: `Codex turn/start failed; could not create replacement thread: ${errToString3(createErr)}`
66671
+ message: `Codex turn/start failed; could not create replacement thread: ${errToString5(createErr)}`
66295
66672
  };
66296
66673
  return;
66297
66674
  }
66298
66675
  this.setActiveTurn(freshThreadId, sink, log2);
66299
66676
  try {
66300
- turnStartResult = await startTurn(freshThreadId);
66677
+ turnId = await startTurn(freshThreadId);
66301
66678
  } catch (retryErr) {
66302
66679
  this.activeTurns.delete(freshThreadId);
66303
66680
  yield {
@@ -66307,7 +66684,7 @@ var CodexAppServerAdapter = class {
66307
66684
  };
66308
66685
  yield {
66309
66686
  type: "error",
66310
- message: `Codex turn/start failed after retry: ${errToString3(retryErr)}`
66687
+ message: `Codex turn/start failed after retry: ${errToString5(retryErr)}`
66311
66688
  };
66312
66689
  return;
66313
66690
  }
@@ -66316,8 +66693,13 @@ var CodexAppServerAdapter = class {
66316
66693
  this.resumedThreadIds.add(freshThreadId);
66317
66694
  threadId = freshThreadId;
66318
66695
  }
66319
- const turnId = extractTurnId(turnStartResult);
66320
- if (turnId)
66696
+ if (!turnId || !sink.input)
66697
+ throw new Error("Codex turn/start returned no turn id");
66698
+ this.injections.bind(sink.input, turnId);
66699
+ sink.flushPending();
66700
+ if (sink.completedTurnId)
66701
+ this.injections.settleTurn(threadId, turnId);
66702
+ else if (!sink.isClosed)
66321
66703
  this.activeTurnIds.set(threadId, turnId);
66322
66704
  yield {
66323
66705
  type: "runtime_session",
@@ -66336,7 +66718,8 @@ var CodexAppServerAdapter = class {
66336
66718
  releasePreparedAttachments();
66337
66719
  this.activeTurns.delete(threadId);
66338
66720
  this.activeTurnIds.delete(threadId);
66339
- this.injections.settleAll(sessionKey);
66721
+ if (sink.input)
66722
+ this.injections.finish(sink.input);
66340
66723
  if (!sawTurnEnd) {
66341
66724
  sink.close();
66342
66725
  }
@@ -66353,7 +66736,7 @@ var CodexAppServerAdapter = class {
66353
66736
  try {
66354
66737
  await this.ensureStarted(log2);
66355
66738
  } catch (err) {
66356
- return { ok: false, message: `Codex app-server failed to start: ${errToString3(err)}` };
66739
+ return { ok: false, message: `Codex app-server failed to start: ${errToString5(err)}` };
66357
66740
  }
66358
66741
  const client = this.client;
66359
66742
  if (!client) {
@@ -66370,7 +66753,7 @@ var CodexAppServerAdapter = class {
66370
66753
  this.instructionsRefresher.recordBaked(sessionKey, threadId, sentInstructions);
66371
66754
  this.resumedThreadIds.add(threadId);
66372
66755
  } catch (err) {
66373
- return { ok: false, message: `Codex thread/start failed: ${errToString3(err)}` };
66756
+ return { ok: false, message: `Codex thread/start failed: ${errToString5(err)}` };
66374
66757
  }
66375
66758
  } else if (isMainSession && !this.resumedThreadIds.has(threadId)) {
66376
66759
  const sentInstructions = this.opts.developerInstructions;
@@ -66380,14 +66763,14 @@ var CodexAppServerAdapter = class {
66380
66763
  this.instructionsRefresher.recordResumed(threadId, sentInstructions);
66381
66764
  this.resumedThreadIds.add(threadId);
66382
66765
  } catch (err) {
66383
- log2?.warn?.(`thread/resume failed (${errToString3(err)}); attempting one-shot fresh-thread start`);
66766
+ log2?.warn?.(`thread/resume failed (${errToString5(err)}); attempting one-shot fresh-thread start`);
66384
66767
  let freshThreadId;
66385
66768
  try {
66386
66769
  freshThreadId = await this.openThread(client, { resumeId: void 0 });
66387
66770
  } catch (innerErr) {
66388
66771
  return {
66389
66772
  ok: false,
66390
- message: `Codex thread/start failed after resume error (persisted thread retained): ${errToString3(innerErr)}`
66773
+ message: `Codex thread/start failed after resume error (persisted thread retained): ${errToString5(innerErr)}`
66391
66774
  };
66392
66775
  }
66393
66776
  this.opts.sessionManager.clearMainThread();
@@ -66468,7 +66851,7 @@ var CodexAppServerAdapter = class {
66468
66851
  this.opts.sessionManager.cleanupFork(fork.sessionKey);
66469
66852
  }
66470
66853
  logForkFailure(err) {
66471
- this.opts.log?.warn?.(`thread/fork failed: ${errToString3(err)}`);
66854
+ this.opts.log?.warn?.(`thread/fork failed: ${errToString5(err)}`);
66472
66855
  return null;
66473
66856
  }
66474
66857
  /**
@@ -66602,16 +66985,17 @@ var CodexAppServerAdapter = class {
66602
66985
  proc.once("close", (code, signal) => this.handleSubprocessClose(proc, code, signal, log2));
66603
66986
  proc.once("error", (err) => this.handleSubprocessClose(proc, null, null, log2, err));
66604
66987
  try {
66605
- await client.sendRequest("initialize", {
66988
+ const initialized2 = await client.sendRequest("initialize", {
66606
66989
  clientInfo: { name: "parall-codex-agent", version: "1" },
66607
66990
  // Required by thread/resume.excludeTurns and thread/fork.excludeTurns.
66608
66991
  // The bridge sends no other experimental request fields. It does not
66609
66992
  // consume thread status snapshots, so suppress them at the source.
66610
66993
  capabilities: {
66611
66994
  experimentalApi: true,
66612
- optOutNotificationMethods: ["thread/status/changed"]
66995
+ optOutNotificationMethods: []
66613
66996
  }
66614
66997
  });
66998
+ requireCodexInputReceipts(initialized2);
66615
66999
  client.sendNotification("initialized", {});
66616
67000
  } catch (err) {
66617
67001
  client.dispose(err instanceof Error ? err : new Error(String(err)));
@@ -66685,47 +67069,20 @@ var CodexAppServerAdapter = class {
66685
67069
  return threadId;
66686
67070
  }
66687
67071
  routeNotification(method, params) {
66688
- for (const tap of this.notificationTaps) {
66689
- try {
66690
- tap(method, params);
66691
- } catch (err) {
66692
- this.opts.log?.warn?.(`notification tap threw: ${errToString3(err)}`);
66693
- }
66694
- }
66695
- const threadId = extractThreadIdFromNotification(params);
66696
- if (!threadId) {
66697
- if (method === "error") {
66698
- const msg = params?.message ?? "Codex app-server error";
66699
- for (const sink2 of this.activeTurns.values()) {
66700
- sink2.push({ kind: "error", message: String(msg) });
66701
- }
66702
- }
66703
- return;
66704
- }
66705
- const sink = this.activeTurns.get(threadId);
66706
- if (!sink) {
66707
- if (this.reconcilingThreadIds.has(threadId))
66708
- return;
66709
- if (this.foreignThreads.route(method, params, threadId))
66710
- return;
66711
- const now = Date.now();
66712
- if (now - this.lastUnroutedNotificationWarnAt > 1e4) {
66713
- this.lastUnroutedNotificationWarnAt = now;
66714
- this.opts.log?.warn?.(`dropping notification "${method}" for unknown thread ${threadId}`);
66715
- }
66716
- return;
66717
- }
66718
- sink.touchActivity();
66719
- for (const event of sink.mapper.map(method, params)) {
66720
- sink.push({ kind: "runtime", event });
66721
- }
66722
- if (method === "turn/completed") {
66723
- this.activeTurnIds.delete(threadId);
66724
- sink.push({ kind: "turn_end", threadId });
66725
- }
67072
+ this.notifications.route({
67073
+ log: this.opts.log,
67074
+ notificationTaps: this.notificationTaps,
67075
+ activeTurns: this.activeTurns,
67076
+ activeTurnIds: this.activeTurnIds,
67077
+ reconcilingThreadIds: this.reconcilingThreadIds,
67078
+ foreignThreads: this.foreignThreads,
67079
+ inputs: this.injections,
67080
+ activity: this.activity,
67081
+ sessionManager: this.opts.sessionManager
67082
+ }, method, params);
66726
67083
  }
66727
67084
  };
66728
- function errToString3(err) {
67085
+ function errToString5(err) {
66729
67086
  if (err instanceof Error)
66730
67087
  return err.message;
66731
67088
  return String(err);