@karlorz/codexhost-cli-win32-x64 0.17.4-7 → 0.17.4-8

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.
@@ -19128,44 +19128,74 @@ var WORKSPACE_CONTRACT_VERSION = 1;
19128
19128
  var THREAD_QUESTIONS_LIST_METHOD = "codexhost/thread/questions/list";
19129
19129
  var THREAD_QUESTION_RESPOND_METHOD = "codexhost/thread/question/respond";
19130
19130
  var THREAD_QUESTION_ACTIVITY_METHOD = "codexhost/thread/question/activity";
19131
- var threadQuestionsParamsSchema = external_exports.strictObject({ threadId: hostThreadIdSchema });
19131
+ var THREAD_QUESTION_RECORDS_LIST_METHOD = "codexhost/thread/question-records/list";
19132
+ var threadQuestionsParamsSchema = external_exports.strictObject({
19133
+ threadId: hostThreadIdSchema,
19134
+ unobserved: external_exports.literal(true).optional()
19135
+ });
19132
19136
  var field = { id: external_exports.string().min(1), prompt: external_exports.string(), optional: external_exports.boolean() };
19133
19137
  var questionAutoResolutionSchema = external_exports.strictObject({
19134
19138
  deadlineUnixMs: external_exports.number().int().min(0).max(864e13),
19135
19139
  action: external_exports.enum(["recommended", "decline"]),
19136
19140
  resetOnActivity: external_exports.boolean().optional()
19137
19141
  });
19142
+ var threadQuestionFieldSchema = external_exports.discriminatedUnion("type", [
19143
+ external_exports.strictObject({
19144
+ ...field,
19145
+ type: external_exports.literal("choice"),
19146
+ multiple: external_exports.boolean(),
19147
+ allowOther: external_exports.boolean(),
19148
+ options: external_exports.array(external_exports.strictObject({
19149
+ value: external_exports.string().min(1),
19150
+ label: external_exports.string(),
19151
+ description: external_exports.string().optional()
19152
+ })).min(1)
19153
+ }),
19154
+ external_exports.strictObject({
19155
+ ...field,
19156
+ type: external_exports.literal("text"),
19157
+ multiline: external_exports.boolean(),
19158
+ secret: external_exports.literal(false),
19159
+ placeholder: external_exports.string().optional(),
19160
+ prefill: external_exports.string().optional()
19161
+ })
19162
+ ]);
19138
19163
  var threadQuestionSchema = external_exports.strictObject({
19139
19164
  interactionId: hostInteractionIdSchema,
19140
19165
  turnId: hostTurnIdSchema,
19141
19166
  title: external_exports.string().optional(),
19142
19167
  expiresAt: external_exports.string().optional(),
19143
19168
  autoResolution: questionAutoResolutionSchema.optional(),
19144
- questions: external_exports.array(external_exports.discriminatedUnion("type", [
19145
- external_exports.strictObject({
19146
- ...field,
19147
- type: external_exports.literal("choice"),
19148
- multiple: external_exports.boolean(),
19149
- allowOther: external_exports.boolean(),
19150
- options: external_exports.array(external_exports.strictObject({
19151
- value: external_exports.string().min(1),
19152
- label: external_exports.string(),
19153
- description: external_exports.string().optional()
19154
- })).min(1)
19155
- }),
19156
- external_exports.strictObject({
19157
- ...field,
19158
- type: external_exports.literal("text"),
19159
- multiline: external_exports.boolean(),
19160
- secret: external_exports.literal(false),
19161
- placeholder: external_exports.string().optional(),
19162
- prefill: external_exports.string().optional()
19163
- })
19164
- ])).min(1)
19169
+ questions: external_exports.array(threadQuestionFieldSchema).min(1)
19165
19170
  });
19166
19171
  var threadQuestionsResultSchema = external_exports.strictObject({
19167
19172
  questions: external_exports.array(threadQuestionSchema)
19168
19173
  });
19174
+ var questionRecordOutcomeSchema = external_exports.enum([
19175
+ "answered",
19176
+ "skipped",
19177
+ "closedByHarness",
19178
+ "expired",
19179
+ "turnEnded"
19180
+ ]);
19181
+ var threadQuestionRecordSchema = external_exports.strictObject({
19182
+ interactionId: hostInteractionIdSchema,
19183
+ turnId: hostTurnIdSchema,
19184
+ itemId: hostItemIdSchema,
19185
+ title: external_exports.string().optional(),
19186
+ questions: external_exports.array(threadQuestionFieldSchema).min(1),
19187
+ outcome: questionRecordOutcomeSchema,
19188
+ answers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string()))
19189
+ });
19190
+ var threadQuestionPendingAnchorSchema = external_exports.strictObject({
19191
+ interactionId: hostInteractionIdSchema,
19192
+ turnId: hostTurnIdSchema,
19193
+ itemId: hostItemIdSchema
19194
+ });
19195
+ var threadQuestionRecordsResultSchema = external_exports.strictObject({
19196
+ records: external_exports.array(threadQuestionRecordSchema),
19197
+ pendingAnchors: external_exports.array(threadQuestionPendingAnchorSchema)
19198
+ });
19169
19199
  var threadQuestionRespondParamsSchema = external_exports.strictObject({
19170
19200
  threadId: hostThreadIdSchema,
19171
19201
  interactionId: hostInteractionIdSchema,
@@ -23716,6 +23746,12 @@ import { homedir as homedir5 } from "node:os";
23716
23746
  import { fileURLToPath as fileURLToPath3 } from "node:url";
23717
23747
 
23718
23748
  // packages/host-runtime/src/external-thread-activity.ts
23749
+ function isActiveSubagent(status2) {
23750
+ return status2 === "pending" || status2 === "running";
23751
+ }
23752
+ function withChildThread(activity, child, resolved) {
23753
+ return resolved.subagentId !== child.nativeSubagentId ? { ...activity, threadId: resolved.subagentId } : activity;
23754
+ }
23719
23755
  async function executeExternalActivity(input) {
23720
23756
  const capability = input.session.backgroundActivity;
23721
23757
  if (!capability)
@@ -23723,7 +23759,7 @@ async function executeExternalActivity(input) {
23723
23759
  const current = () => {
23724
23760
  if (!input.isCurrent()) throw new Error("Background activity Session changed");
23725
23761
  };
23726
- const resolveChildren = async (activities) => {
23762
+ const resolveChildren = async (activities, mode) => {
23727
23763
  const children = capability.subagents?.() ?? [];
23728
23764
  return Promise.all(
23729
23765
  activities.map(async (activity) => {
@@ -23731,9 +23767,14 @@ async function executeExternalActivity(input) {
23731
23767
  const child = children.find((entry) => entry.activityId === activity.id)?.state;
23732
23768
  if (!child) return activity;
23733
23769
  current();
23770
+ if (mode === "list" && !isActiveSubagent(child.status)) {
23771
+ const existing = await input.lookup?.(child);
23772
+ current();
23773
+ return existing ? withChildThread(activity, child, existing) : activity;
23774
+ }
23734
23775
  const resolved = await input.materialize(child);
23735
23776
  current();
23736
- return resolved.subagentId !== child.nativeSubagentId ? { ...activity, threadId: resolved.subagentId } : activity;
23777
+ return withChildThread(activity, child, resolved);
23737
23778
  })
23738
23779
  );
23739
23780
  };
@@ -23743,14 +23784,18 @@ async function executeExternalActivity(input) {
23743
23784
  const result2 = await capability.list();
23744
23785
  current();
23745
23786
  if (!result2.ok) return failure(result2.error);
23746
- const activities = await resolveChildren(result2.value);
23787
+ if (input.afterList) {
23788
+ await input.afterList();
23789
+ current();
23790
+ }
23791
+ const activities = await resolveChildren(result2.value, "list");
23747
23792
  return { result: threadActivityListResultSchema.parse({ supported: true, activities }) };
23748
23793
  }
23749
23794
  if (input.method === THREAD_ACTIVITY_READ_METHOD) {
23750
23795
  const result2 = await capability.read(input.activityId ?? "");
23751
23796
  current();
23752
23797
  if (!result2.ok) return failure(result2.error);
23753
- const [activity] = await resolveChildren([result2.value.activity]);
23798
+ const [activity] = await resolveChildren([result2.value.activity], "read");
23754
23799
  return { result: backgroundActivityDetailSchema.parse({ ...result2.value, activity }) };
23755
23800
  }
23756
23801
  const result = await capability.stop(input.activityId ?? "");
@@ -24198,7 +24243,9 @@ var storedThreadCoreV1Shape = {
24198
24243
  subagent: external_exports.object({
24199
24244
  parentHostThreadId: hostThreadIdSchema,
24200
24245
  nativeSubagentId: nonBlankTextSchema6.max(1024),
24201
- role: external_exports.string().max(1024).optional()
24246
+ role: external_exports.string().max(1024).optional(),
24247
+ /** Present when this child is a Harness scheduled/loop run rather than a model-delegated Subagent. */
24248
+ origin: external_exports.literal("scheduled").optional()
24202
24249
  }).strict().optional(),
24203
24250
  turnMappings: external_exports.array(storedTurnMappingV1Schema),
24204
24251
  createdAt: isoDateSchema,
@@ -25040,6 +25087,14 @@ var MappingStore = class {
25040
25087
  async setArchived(hostThreadId, archived) {
25041
25088
  return this.#update(hostThreadId, (current) => current.archived === archived ? null : { ...current, archived });
25042
25089
  }
25090
+ /** Tags a child record's origin only when it is still missing. */
25091
+ async setSubagentOrigin(hostThreadId, origin) {
25092
+ return this.#update(hostThreadId, (current) => {
25093
+ if (!current.subagent || current.subagent.origin !== void 0)
25094
+ return null;
25095
+ return { ...current, subagent: { ...current.subagent, origin } };
25096
+ });
25097
+ }
25043
25098
  /**
25044
25099
  * Patch Desktop metadata. With `ifProjectId`, the patch applies only while the
25045
25100
  * stored assignment still equals it; otherwise the current record is returned.
@@ -36958,7 +37013,7 @@ function subagentMaterializer(store, parent, previousParent) {
36958
37013
  const { byRequest } = await legacyRecords();
36959
37014
  existing = byRequest.get(createRequestId) ?? (previousRequest ? byRequest.get(previousRequest) : void 0) ?? null;
36960
37015
  }
36961
- const configured = (record6) => child.model !== void 0 || child.reasoningEffort !== void 0 ? store.updateMetadata(record6.hostThreadId, {
37016
+ const configured = async (record6) => child.model !== void 0 || child.reasoningEffort !== void 0 ? store.updateMetadata(record6.hostThreadId, {
36962
37017
  subagentConfiguration: {
36963
37018
  ...child.model !== void 0 ? { model: child.model } : {},
36964
37019
  ...child.reasoningEffort !== void 0 ? { reasoningEffort: child.reasoningEffort } : {}
@@ -36966,10 +37021,11 @@ function subagentMaterializer(store, parent, previousParent) {
36966
37021
  }) : record6;
36967
37022
  if (existing?.state === "ready") {
36968
37023
  if (existing.nativeSessionRef?.nativeSessionId === nativeRef.nativeSessionId)
36969
- return configured(existing);
37024
+ return { record: await configured(existing), created: false };
36970
37025
  if (!previousRef) throw new Error("Subagent belongs to a different Native Session");
36971
- return configured(await rebind(existing, parent));
37026
+ return { record: await configured(await rebind(existing, parent)), created: false };
36972
37027
  }
37028
+ const created = !existing;
36973
37029
  const provisional = existing ?? await store.createProvisional({
36974
37030
  hostThreadId: hostThreadIdSchema.parse(randomUUID12()),
36975
37031
  createRequestId,
@@ -36982,20 +37038,35 @@ function subagentMaterializer(store, parent, previousParent) {
36982
37038
  subagent: {
36983
37039
  parentHostThreadId: parent.hostThreadId,
36984
37040
  nativeSubagentId: child.nativeSubagentId,
36985
- ...child.role ? { role: child.role } : {}
37041
+ ...child.role ? { role: child.role } : {},
37042
+ ...child.origin ? { origin: child.origin } : {}
36986
37043
  }
36987
37044
  });
36988
- return configured(
36989
- provisional.state === "ready" ? provisional : await store.commitReady({
36990
- hostThreadId: provisional.hostThreadId,
36991
- nativeSessionRef: nativeRef
36992
- })
36993
- );
37045
+ return {
37046
+ record: await configured(
37047
+ provisional.state === "ready" ? provisional : await store.commitReady({
37048
+ hostThreadId: provisional.hostThreadId,
37049
+ nativeSessionRef: nativeRef
37050
+ })
37051
+ ),
37052
+ created
37053
+ };
36994
37054
  };
36995
37055
  }
36996
- async function materializeExternalSubagent(store, parent, child) {
37056
+ async function lookupExternalSubagent(store, parent, child) {
37057
+ if (!child.nativeSubagentId || !parent.nativeSessionRef || parent.state !== "ready") return null;
37058
+ const existing = await store.getThreadByCreateRequest(
37059
+ childCreateRequest(parent, parent.nativeSessionRef, child.nativeSubagentId)
37060
+ );
37061
+ return existing?.state === "ready" && existing.nativeSessionRef?.nativeSessionId === parent.nativeSessionRef.nativeSessionId ? existing : null;
37062
+ }
37063
+ async function materializeExternalSubagentResult(store, parent, child) {
36997
37064
  return subagentMaterializer(store, parent)(child);
36998
37065
  }
37066
+ async function materializeExternalSubagent(store, parent, child) {
37067
+ const result = await materializeExternalSubagentResult(store, parent, child);
37068
+ return result?.record ?? null;
37069
+ }
36999
37070
  async function projectExternalSnapshot(store, record6, snapshot2, previousParent) {
37000
37071
  const materialize = subagentMaterializer(store, record6, previousParent);
37001
37072
  const turns = [];
@@ -37008,7 +37079,7 @@ async function projectExternalSnapshot(store, record6, snapshot2, previousParent
37008
37079
  const subagents = await Promise.all(
37009
37080
  entry.item.subagents.map(async (child) => {
37010
37081
  const stored = await materialize(child);
37011
- return stored ? { ...child, subagentId: stored.hostThreadId } : child;
37082
+ return stored ? { ...child, subagentId: stored.record.hostThreadId } : child;
37012
37083
  })
37013
37084
  );
37014
37085
  return { ...entry, item: { ...entry.item, subagents } };
@@ -37073,6 +37144,12 @@ var ExternalThreadRepository = class {
37073
37144
  materializeSubagent(parent, child) {
37074
37145
  return materializeExternalSubagent(this.store, parent, child);
37075
37146
  }
37147
+ materializeSubagentResult(parent, child) {
37148
+ return materializeExternalSubagentResult(this.store, parent, child);
37149
+ }
37150
+ lookupSubagent(parent, child) {
37151
+ return lookupExternalSubagent(this.store, parent, child);
37152
+ }
37076
37153
  findByCreateRequest(createRequestId) {
37077
37154
  return this.store.getThreadByCreateRequest(createRequestId);
37078
37155
  }
@@ -37115,6 +37192,9 @@ var ExternalThreadRepository = class {
37115
37192
  setArchived(hostThreadId, archived) {
37116
37193
  return this.store.setArchived(hostThreadId, archived);
37117
37194
  }
37195
+ setSubagentOrigin(hostThreadId, origin) {
37196
+ return this.store.setSubagentOrigin(hostThreadId, origin);
37197
+ }
37118
37198
  updateMetadata(hostThreadId, patch, options) {
37119
37199
  return this.store.updateMetadata(hostThreadId, patch, options);
37120
37200
  }
@@ -37894,6 +37974,121 @@ function validateSharedQuestionResponse(interaction, response) {
37894
37974
  }
37895
37975
  }
37896
37976
 
37977
+ // packages/host-runtime/src/question-records.ts
37978
+ var LOCKED = /* @__PURE__ */ new Set(["answered", "skipped", "expired"]);
37979
+ var MAX_RECORDS_PER_THREAD = 100;
37980
+ function publicQuestions(questions) {
37981
+ const fields = [];
37982
+ for (const question of questions) {
37983
+ if (question.type === "text") {
37984
+ if (question.secret) continue;
37985
+ const parsed3 = threadQuestionFieldSchema.safeParse({
37986
+ id: question.id,
37987
+ type: "text",
37988
+ prompt: question.prompt,
37989
+ optional: question.optional,
37990
+ multiline: question.multiline,
37991
+ secret: false,
37992
+ ...question.placeholder !== void 0 ? { placeholder: question.placeholder } : {},
37993
+ ...question.prefill !== void 0 ? { prefill: question.prefill } : {}
37994
+ });
37995
+ if (parsed3.success) fields.push(parsed3.data);
37996
+ continue;
37997
+ }
37998
+ const parsed2 = threadQuestionFieldSchema.safeParse({
37999
+ id: question.id,
38000
+ type: "choice",
38001
+ prompt: question.prompt,
38002
+ optional: question.optional,
38003
+ multiple: question.multiple,
38004
+ allowOther: question.allowOther,
38005
+ options: question.options
38006
+ });
38007
+ if (parsed2.success) fields.push(parsed2.data);
38008
+ }
38009
+ return fields.length > 0 ? fields : null;
38010
+ }
38011
+ function publicAnswers(answers, questions) {
38012
+ const allowed = new Set(questions.map((question) => question.id));
38013
+ return Object.fromEntries(
38014
+ Object.entries(answers).filter(([id2, values]) => allowed.has(id2) && values.length > 0)
38015
+ );
38016
+ }
38017
+ function toRecord(input) {
38018
+ const questions = publicQuestions(input.questions);
38019
+ if (!questions) return null;
38020
+ const interactionId = hostInteractionIdSchema.safeParse(input.interactionId);
38021
+ const turnId = hostTurnIdSchema.safeParse(input.turnId);
38022
+ const itemId = hostItemIdSchema.safeParse(input.itemId);
38023
+ if (!interactionId.success || !turnId.success || !itemId.success) return null;
38024
+ const parsed2 = threadQuestionRecordSchema.safeParse({
38025
+ interactionId: interactionId.data,
38026
+ turnId: turnId.data,
38027
+ itemId: itemId.data,
38028
+ ...input.title !== void 0 ? { title: input.title } : {},
38029
+ questions,
38030
+ outcome: input.outcome,
38031
+ answers: publicAnswers(input.answers, questions)
38032
+ });
38033
+ return parsed2.success ? parsed2.data : null;
38034
+ }
38035
+ var QuestionRecordStore = class {
38036
+ #records = /* @__PURE__ */ new WeakMap();
38037
+ #map(thread) {
38038
+ const existing = this.#records.get(thread);
38039
+ if (existing) return existing;
38040
+ const created = /* @__PURE__ */ new Map();
38041
+ this.#records.set(thread, created);
38042
+ return created;
38043
+ }
38044
+ #write(thread, record6) {
38045
+ const records = this.#map(thread);
38046
+ const current = records.get(record6.interactionId);
38047
+ if (current && LOCKED.has(current.outcome)) return;
38048
+ if (!records.has(record6.interactionId) && records.size >= MAX_RECORDS_PER_THREAD) {
38049
+ const oldest = records.keys().next().value;
38050
+ if (oldest !== void 0) records.delete(oldest);
38051
+ }
38052
+ records.set(record6.interactionId, record6);
38053
+ }
38054
+ record(thread, input) {
38055
+ const next = toRecord({
38056
+ interactionId: input.interaction.interactionId,
38057
+ turnId: input.interaction.turnId,
38058
+ itemId: input.itemId,
38059
+ ...input.interaction.title !== void 0 ? { title: input.interaction.title } : {},
38060
+ questions: input.interaction.questions,
38061
+ outcome: input.outcome,
38062
+ answers: input.answers
38063
+ });
38064
+ if (next) this.#write(thread, next);
38065
+ }
38066
+ ingest(thread, turnId, item) {
38067
+ if (item.type !== "toolExecution" || !item.questionRecord) return;
38068
+ const evidence = item.questionRecord;
38069
+ const questions = evidence.questions;
38070
+ const next = toRecord({
38071
+ interactionId: evidence.interactionId ?? item.itemId,
38072
+ turnId,
38073
+ itemId: item.itemId,
38074
+ ...evidence.title !== void 0 ? { title: evidence.title } : {},
38075
+ questions,
38076
+ outcome: evidence.outcome,
38077
+ answers: evidence.answers
38078
+ });
38079
+ if (next) this.#write(thread, next);
38080
+ }
38081
+ ingestHistory(thread, turns) {
38082
+ for (const turn of turns) {
38083
+ for (const item of turn.items) this.ingest(thread, turn.turnId, item);
38084
+ }
38085
+ }
38086
+ list(thread) {
38087
+ if (!thread) return [];
38088
+ return [...this.#map(thread).values()];
38089
+ }
38090
+ };
38091
+
37897
38092
  // packages/host-runtime/src/external-thread-history.ts
37898
38093
  var DEFAULT_PAGE_SIZE2 = 25;
37899
38094
  var MAX_PAGE_SIZE2 = 100;
@@ -44419,7 +44614,7 @@ function externalAnchor(entry) {
44419
44614
  if (entry.source !== "external") throw new Error("Expected an External Thread list entry");
44420
44615
  return { timestamp: entry.timestamp, threadId: threadId(entry.thread) };
44421
44616
  }
44422
- function includesExternalRecord(record6, query, byId, sectionId) {
44617
+ function includesExternalRecord(record6, query, byId, sectionId, runtime) {
44423
44618
  if (record6.state !== "ready" || !record6.nativeSessionRef) return false;
44424
44619
  let current = record6;
44425
44620
  const owners = /* @__PURE__ */ new Set();
@@ -44435,6 +44630,7 @@ function includesExternalRecord(record6, query, byId, sectionId) {
44435
44630
  const scoped = query.parentThreadId !== null || query.ancestorThreadId !== null;
44436
44631
  if (record6.subagent && !scoped && !query.sourceKinds?.some((kind) => kind === "subAgent" || kind === "subAgentThreadSpawn"))
44437
44632
  return false;
44633
+ if (scoped && record6.subagent?.origin === "scheduled" && runtime?.running !== true) return false;
44438
44634
  if (query.parentThreadId !== null && record6.subagent?.parentHostThreadId !== query.parentThreadId)
44439
44635
  return false;
44440
44636
  if (query.ancestorThreadId !== null) {
@@ -44504,7 +44700,8 @@ function externalThreadListEntries(input) {
44504
44700
  record6,
44505
44701
  input.query,
44506
44702
  byId,
44507
- input.placementOf?.(record6.hostThreadId)?.section.id ?? null
44703
+ input.placementOf?.(record6.hostThreadId)?.section.id ?? null,
44704
+ input.runtimeFor(record6.hostThreadId)
44508
44705
  )
44509
44706
  ).map((record6) => {
44510
44707
  const runtime = input.runtimeFor(record6.hostThreadId);
@@ -45356,6 +45553,8 @@ var AppServerHost = class {
45356
45553
  #repository;
45357
45554
  #pendingDesktopApprovals = /* @__PURE__ */ new Map();
45358
45555
  #pendingDesktopQuestions = /* @__PURE__ */ new Map();
45556
+ #questionRecords = new QuestionRecordStore();
45557
+ #questionHistoryIngested = /* @__PURE__ */ new WeakSet();
45359
45558
  #nextApprovalRequestId = HOST_APPROVAL_REQUEST_ID_MAX;
45360
45559
  #nextQuestionRequestId = HOST_QUESTION_REQUEST_ID_MAX;
45361
45560
  #delegationCoordinator;
@@ -45381,6 +45580,7 @@ var AppServerHost = class {
45381
45580
  #nextConsoleRequest = 0;
45382
45581
  #subagentThreadStatuses = /* @__PURE__ */ new Map();
45383
45582
  #runningSubagentsByParent = /* @__PURE__ */ new Map();
45583
+ #scheduledOriginBackfilled = /* @__PURE__ */ new Set();
45384
45584
  #pendingExternalCommandRequests = /* @__PURE__ */ new Set();
45385
45585
  #manualCompactionTurns = /* @__PURE__ */ new WeakMap();
45386
45586
  #closeRequested = false;
@@ -46056,7 +46256,12 @@ var AppServerHost = class {
46056
46256
  method: request.method,
46057
46257
  ..."activityId" in parsed2.data ? { activityId: String(parsed2.data.activityId) } : {},
46058
46258
  isCurrent: () => this.#externalRuntime.get(thread.id) === thread,
46059
- materialize: (child) => this.#materializeSubagent(thread, child)
46259
+ materialize: (child) => this.#materializeSubagent(thread, child),
46260
+ lookup: async (child) => {
46261
+ const record6 = await this.#repository.lookupSubagent(thread.record, child);
46262
+ return record6 ? { ...child, subagentId: record6.hostThreadId } : null;
46263
+ },
46264
+ afterList: () => this.#backfillScheduledSubagentOrigins(thread)
46060
46265
  });
46061
46266
  await this.#writer.json(
46062
46267
  result.error ? rpcError(request, result.error.code, result.error.message) : rpcEnvelope(request, { result: jsonValueSchema.parse(result.result) })
@@ -46064,7 +46269,7 @@ var AppServerHost = class {
46064
46269
  });
46065
46270
  return;
46066
46271
  }
46067
- if (request.method === THREAD_QUESTIONS_LIST_METHOD || request.method === THREAD_QUESTION_RESPOND_METHOD || request.method === THREAD_QUESTION_ACTIVITY_METHOD) {
46272
+ if (request.method === THREAD_QUESTIONS_LIST_METHOD || request.method === THREAD_QUESTION_RESPOND_METHOD || request.method === THREAD_QUESTION_ACTIVITY_METHOD || request.method === THREAD_QUESTION_RECORDS_LIST_METHOD) {
46068
46273
  await this.#handleSharedQuestionRequest(request);
46069
46274
  return;
46070
46275
  }
@@ -49628,8 +49833,10 @@ var AppServerHost = class {
49628
49833
  if (event.type === "session.faulted") {
49629
49834
  this.#externalVoiceResults.observe(thread.id, event);
49630
49835
  for (const pending of [...this.#pendingDesktopQuestions.values()]) {
49631
- if (pending.extended && pending.thread === thread)
49632
- this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
49836
+ if (pending.extended && pending.thread === thread) {
49837
+ this.#rememberQuestion(pending, "closedByHarness", {});
49838
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, thread);
49839
+ }
49633
49840
  }
49634
49841
  this.#externalSteering.fault(thread.id, new Error(event.error.message));
49635
49842
  thread.stateObserver.fault(new Error(event.error.message));
@@ -49671,6 +49878,11 @@ var AppServerHost = class {
49671
49878
  }
49672
49879
  const projection = this.#projectedTurn(thread, event.turnId);
49673
49880
  await this.#waitForTurnResponse(thread, event.turnId);
49881
+ if (event.type === "item.started")
49882
+ this.#questionRecords.ingest(thread, event.turnId, event.item);
49883
+ if (event.type === "item.completed") {
49884
+ this.#questionRecords.ingest(thread, event.turnId, event.snapshot.item);
49885
+ }
49674
49886
  if (event.type === "item.completed" && event.snapshot.item.type === "agentMessage" && this.#externalVoice.has(thread.id)) {
49675
49887
  projection.realtimeInline = true;
49676
49888
  }
@@ -49679,12 +49891,16 @@ var AppServerHost = class {
49679
49891
  }
49680
49892
  if (event.type === "turn.completed") {
49681
49893
  for (const pending of [...this.#pendingDesktopQuestions.values()]) {
49682
- if (pending.extended && pending.thread === thread && pending.interaction.turnId === event.turnId)
49683
- this.#retireDesktopQuestion(pending.interaction.interactionId, thread);
49894
+ if (pending.extended && pending.thread === thread && pending.interaction.turnId === event.turnId) {
49895
+ this.#rememberQuestion(pending, "turnEnded", {});
49896
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, thread);
49897
+ }
49684
49898
  }
49685
49899
  }
49686
49900
  if (event.type === "interaction.closed") {
49687
49901
  await this.#resolveDesktopApproval(event.interactionId, thread);
49902
+ const pending = this.#pendingQuestion(event.interactionId, thread);
49903
+ if (pending) this.#rememberQuestion(pending, "closedByHarness", {});
49688
49904
  await this.#resolveDesktopQuestion(event.interactionId, thread);
49689
49905
  }
49690
49906
  const ephemeralTurn = event.type === "turn.completed" && (event.ephemeral === true || thread.ephemeralTurnIds.has(event.turnId));
@@ -49772,11 +49988,29 @@ var AppServerHost = class {
49772
49988
  }
49773
49989
  }
49774
49990
  }
49991
+ async #backfillScheduledSubagentOrigins(parent) {
49992
+ if (this.#scheduledOriginBackfilled.has(parent.id)) return;
49993
+ this.#scheduledOriginBackfilled.add(parent.id);
49994
+ try {
49995
+ const children = parent.session.backgroundActivity?.subagents?.() ?? [];
49996
+ for (const { state } of children) {
49997
+ if (state.origin !== "scheduled") continue;
49998
+ const record6 = await this.#repository.lookupSubagent(parent.record, state);
49999
+ if (!record6?.subagent || record6.subagent.origin !== void 0) continue;
50000
+ const updated = await this.#repository.setSubagentOrigin(record6.hostThreadId, "scheduled");
50001
+ const loaded = this.#externalRuntime.get(updated.hostThreadId);
50002
+ if (loaded) loaded.record = updated;
50003
+ }
50004
+ } catch (error51) {
50005
+ this.#diagnose(error51);
50006
+ }
50007
+ }
49775
50008
  async #materializeSubagent(parent, subagent) {
49776
50009
  if (!subagent.nativeSubagentId || !parent.record.nativeSessionRef) return subagent;
49777
50010
  const status2 = subagent.status === "pending" || subagent.status === "running" ? "active" : "idle";
49778
- const record6 = await this.#repository.materializeSubagent(parent.record, subagent);
49779
- if (!record6) return subagent;
50011
+ const materialized = await this.#repository.materializeSubagentResult(parent.record, subagent);
50012
+ if (!materialized) return subagent;
50013
+ const { record: record6, created } = materialized;
49780
50014
  const loaded = this.#externalRuntime.get(record6.hostThreadId);
49781
50015
  if (loaded) {
49782
50016
  loaded.record = record6;
@@ -49791,19 +50025,21 @@ var AppServerHost = class {
49791
50025
  await this.#setSubagentThreadStatus(record6.hostThreadId, status2);
49792
50026
  return { ...subagent, subagentId: record6.hostThreadId };
49793
50027
  }
49794
- const thread = externalThreadValue({
49795
- record: record6,
49796
- turns: [],
49797
- sessionId: parent.sessionId,
49798
- running: status2 === "active"
49799
- });
49800
50028
  this.#subagentThreadStatuses.set(record6.hostThreadId, status2);
49801
50029
  this.#trackRunningSubagent(parent.id, record6.hostThreadId, status2);
49802
- await this.#writer.json({
49803
- method: "thread/started",
49804
- emittedAtMs: Date.now(),
49805
- params: { thread }
49806
- });
50030
+ if (created || status2 === "active") {
50031
+ const thread = externalThreadValue({
50032
+ record: record6,
50033
+ turns: [],
50034
+ sessionId: parent.sessionId,
50035
+ running: status2 === "active"
50036
+ });
50037
+ await this.#writer.json({
50038
+ method: "thread/started",
50039
+ emittedAtMs: Date.now(),
50040
+ params: { thread }
50041
+ });
50042
+ }
49807
50043
  return { ...subagent, subagentId: record6.hostThreadId };
49808
50044
  }
49809
50045
  async #refreshOpenSubagentThread(threadId2, terminal3 = true) {
@@ -50027,8 +50263,10 @@ var AppServerHost = class {
50027
50263
  await this.#resolveDesktopApproval(pending.interaction.interactionId, thread);
50028
50264
  }
50029
50265
  for (const pending of [...this.#pendingDesktopQuestions.values()]) {
50030
- if (pending.thread === thread)
50266
+ if (pending.thread === thread) {
50267
+ this.#rememberQuestion(pending, "closedByHarness", {});
50031
50268
  await this.#resolveDesktopQuestion(pending.interaction.interactionId, thread);
50269
+ }
50032
50270
  }
50033
50271
  }
50034
50272
  async #resolveDesktopApproval(interactionId, thread) {
@@ -50051,6 +50289,48 @@ var AppServerHost = class {
50051
50289
  return requestId2;
50052
50290
  }
50053
50291
  async #handleSharedQuestionRequest(request) {
50292
+ if (request.method === THREAD_QUESTION_RECORDS_LIST_METHOD) {
50293
+ const parsed2 = threadQuestionsParamsSchema.safeParse(request.params);
50294
+ if (!parsed2.success) {
50295
+ await this.#writer.json(rpcError(request, -32602, "Invalid question record list request"));
50296
+ return;
50297
+ }
50298
+ const thread = this.#externalRuntime.get(parsed2.data.threadId);
50299
+ if (thread && !this.#questionHistoryIngested.has(thread)) {
50300
+ const snapshot2 = await thread.session.readSnapshot();
50301
+ if (snapshot2.ok) {
50302
+ this.#questionHistoryIngested.add(thread);
50303
+ this.#questionRecords.ingestHistory(
50304
+ thread,
50305
+ snapshot2.value.turns.flatMap((turn, index) => {
50306
+ const turnId = thread.record.turnMappings[index]?.hostTurnId;
50307
+ if (!turnId) return [];
50308
+ return [{ turnId, items: turn.items.map((entry) => entry.item) }];
50309
+ })
50310
+ );
50311
+ }
50312
+ }
50313
+ const pendingAnchors = [...this.#pendingDesktopQuestions.values()].flatMap(
50314
+ (pending) => pending.thread.id === parsed2.data.threadId ? [
50315
+ {
50316
+ interactionId: pending.interaction.interactionId,
50317
+ turnId: pending.interaction.turnId,
50318
+ itemId: pending.itemId
50319
+ }
50320
+ ] : []
50321
+ );
50322
+ await this.#writer.json(
50323
+ rpcEnvelope(request, {
50324
+ result: jsonValueSchema.parse(
50325
+ threadQuestionRecordsResultSchema.parse({
50326
+ records: this.#questionRecords.list(thread),
50327
+ pendingAnchors
50328
+ })
50329
+ )
50330
+ })
50331
+ );
50332
+ return;
50333
+ }
50054
50334
  if (request.method === THREAD_QUESTIONS_LIST_METHOD) {
50055
50335
  const parsed2 = threadQuestionsParamsSchema.safeParse(request.params);
50056
50336
  if (!parsed2.success) {
@@ -50060,6 +50340,9 @@ var AppServerHost = class {
50060
50340
  const questions = [...this.#pendingDesktopQuestions.values()].filter(
50061
50341
  (pending) => pending.extended && pending.thread.id === parsed2.data.threadId && this.#isCurrentSharedQuestion(pending)
50062
50342
  ).map(({ interaction }) => sharedQuestion(interaction));
50343
+ await this.#syncDesktopQuestionNotifiers(
50344
+ parsed2.data.unobserved ? null : parsed2.data.threadId
50345
+ );
50063
50346
  await this.#writer.json(
50064
50347
  rpcEnvelope(request, {
50065
50348
  result: jsonValueSchema.parse(threadQuestionsResultSchema.parse({ questions }))
@@ -50134,15 +50417,23 @@ var AppServerHost = class {
50134
50417
  response
50135
50418
  });
50136
50419
  if (!result.ok) {
50137
- if (result.error.code === "invalidState")
50138
- this.#retireDesktopQuestion(params.interactionId, pending.thread);
50420
+ if (result.error.code === "invalidState") {
50421
+ this.#rememberQuestion(pending, "closedByHarness", {});
50422
+ await this.#resolveDesktopQuestion(params.interactionId, pending.thread);
50423
+ }
50139
50424
  await this.#writer.json(rpcError(request, -32080, result.error.message));
50140
50425
  return;
50141
50426
  }
50142
- this.#retireDesktopQuestion(params.interactionId, pending.thread);
50427
+ this.#rememberQuestion(
50428
+ pending,
50429
+ response.cancelled ? "skipped" : "answered",
50430
+ response.answers
50431
+ );
50432
+ await this.#resolveDesktopQuestion(params.interactionId, pending.thread);
50143
50433
  await this.#writer.json(rpcEnvelope(request, { result: { accepted: true } }));
50144
50434
  } catch (error51) {
50145
- this.#retireDesktopQuestion(params.interactionId, pending.thread);
50435
+ this.#rememberQuestion(pending, "closedByHarness", {});
50436
+ await this.#resolveDesktopQuestion(params.interactionId, pending.thread);
50146
50437
  await this.#writer.json(rpcError(request, -32080, errorMessage4(error51)));
50147
50438
  } finally {
50148
50439
  pending.responding = false;
@@ -50192,35 +50483,69 @@ var AppServerHost = class {
50192
50483
  }
50193
50484
  for (const message2 of result.messages) await this.#writer.json(message2);
50194
50485
  const requestId2 = this.#allocateQuestionRequestId();
50195
- const expiresAtMs = interaction.expiresAt ? Date.parse(interaction.expiresAt) : Number.NaN;
50196
- const timeoutMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - Date.now()) : null;
50197
50486
  const pending = {
50198
50487
  responding: false,
50199
50488
  thread,
50200
50489
  interaction,
50201
50490
  projection: result.questionRequest,
50491
+ itemId: result.itemId,
50202
50492
  timeout: null,
50203
- extended: shared
50493
+ extended: shared,
50494
+ desktopNotified: false
50204
50495
  };
50205
- if (timeoutMs !== null) {
50206
- pending.timeout = setTimeout(() => {
50207
- void this.#cancelExpiredQuestion(requestId2).catch((error51) => this.#diagnose(error51));
50208
- }, timeoutMs);
50209
- }
50210
50496
  this.#pendingDesktopQuestions.set(requestId2, pending);
50211
- if (pending.extended) return;
50497
+ this.#scheduleQuestionTimeout(requestId2, pending);
50498
+ if (shared) return;
50499
+ await this.#notifyDesktopQuestion(requestId2, pending);
50500
+ }
50501
+ async #notifyDesktopQuestion(requestId2, pending) {
50502
+ if (pending.desktopNotified) return;
50503
+ pending.desktopNotified = true;
50212
50504
  try {
50213
- await this.#writer.json({ id: requestId2, ...result.questionRequest.request });
50505
+ await this.#writer.json({ id: requestId2, ...pending.projection.request });
50214
50506
  } catch (error51) {
50215
- this.#retireDesktopQuestion(interaction.interactionId, thread);
50216
- await thread.session.execute({
50507
+ pending.desktopNotified = false;
50508
+ await this.#resolveDesktopQuestion(pending.interaction.interactionId, pending.thread);
50509
+ await pending.thread.session.execute({
50217
50510
  type: "interaction.respond",
50218
- interactionId: interaction.interactionId,
50511
+ interactionId: pending.interaction.interactionId,
50219
50512
  response: { type: "question", answers: {}, cancelled: true }
50220
50513
  }).catch(() => void 0);
50221
50514
  throw error51;
50222
50515
  }
50223
50516
  }
50517
+ async #armDesktopQuestionNotifiers(visibleThreadId) {
50518
+ for (const [requestId2, pending] of this.#pendingDesktopQuestions) {
50519
+ if (!pending.extended || pending.desktopNotified || visibleThreadId !== null && pending.thread.id === visibleThreadId)
50520
+ continue;
50521
+ if (!this.#isCurrentSharedQuestion(pending)) continue;
50522
+ try {
50523
+ await this.#notifyDesktopQuestion(requestId2, pending);
50524
+ } catch (error51) {
50525
+ this.#diagnose(error51);
50526
+ }
50527
+ }
50528
+ }
50529
+ async #releaseDesktopQuestionNotifier(visibleThreadId) {
50530
+ for (const [requestId2, pending] of [...this.#pendingDesktopQuestions]) {
50531
+ if (!pending.extended || !pending.desktopNotified) continue;
50532
+ if (pending.thread.id !== visibleThreadId) continue;
50533
+ if (!this.#isCurrentSharedQuestion(pending)) continue;
50534
+ pending.desktopNotified = false;
50535
+ this.#pendingDesktopQuestions.delete(requestId2);
50536
+ const nextId = this.#allocateQuestionRequestId();
50537
+ this.#pendingDesktopQuestions.set(nextId, pending);
50538
+ this.#scheduleQuestionTimeout(nextId, pending);
50539
+ await this.#writer.json({
50540
+ method: "serverRequest/resolved",
50541
+ params: { threadId: pending.thread.id, requestId: requestId2 }
50542
+ });
50543
+ }
50544
+ }
50545
+ async #syncDesktopQuestionNotifiers(visibleThreadId) {
50546
+ if (visibleThreadId !== null) await this.#releaseDesktopQuestionNotifier(visibleThreadId);
50547
+ await this.#armDesktopQuestionNotifiers(visibleThreadId);
50548
+ }
50224
50549
  async #handleDesktopQuestionResponse(value2) {
50225
50550
  if (!isRecord21(value2) || !isHostQuestionRequestId(value2.id)) return false;
50226
50551
  const requestId2 = value2.id;
@@ -50241,6 +50566,11 @@ var AppServerHost = class {
50241
50566
  this.#diagnose(error51);
50242
50567
  response = { type: "question", answers: {}, cancelled: true };
50243
50568
  }
50569
+ this.#rememberQuestion(
50570
+ pending,
50571
+ response.cancelled ? "skipped" : "answered",
50572
+ response.answers
50573
+ );
50244
50574
  const result = await pending.thread.session.execute({
50245
50575
  type: "interaction.respond",
50246
50576
  interactionId: pending.interaction.interactionId,
@@ -50258,6 +50588,7 @@ var AppServerHost = class {
50258
50588
  await this.#externalRuntime.idleRelease.runOperation(pending.thread.id, async () => {
50259
50589
  if (this.#externalRuntime.get(pending.thread.id) !== pending.thread || this.#externalRuntime.idleRelease.failure(pending.thread))
50260
50590
  return;
50591
+ this.#rememberQuestion(pending, "expired", {});
50261
50592
  await this.#resolveDesktopQuestion(pending.interaction.interactionId, pending.thread);
50262
50593
  if (pending.responding) return;
50263
50594
  const result = await pending.thread.session.execute({
@@ -50270,13 +50601,20 @@ var AppServerHost = class {
50270
50601
  }
50271
50602
  });
50272
50603
  }
50273
- #retireDesktopQuestion(interactionId, thread) {
50274
- for (const [requestId2, pending] of this.#pendingDesktopQuestions) {
50275
- if (pending.thread !== thread || pending.interaction.interactionId !== interactionId)
50276
- continue;
50277
- if (pending.timeout) clearTimeout(pending.timeout);
50278
- this.#pendingDesktopQuestions.delete(requestId2);
50604
+ #pendingQuestion(interactionId, thread) {
50605
+ for (const pending of this.#pendingDesktopQuestions.values()) {
50606
+ if (pending.thread === thread && pending.interaction.interactionId === interactionId)
50607
+ return pending;
50279
50608
  }
50609
+ return void 0;
50610
+ }
50611
+ #rememberQuestion(pending, outcome, answers) {
50612
+ this.#questionRecords.record(pending.thread, {
50613
+ interaction: pending.interaction,
50614
+ itemId: pending.itemId,
50615
+ outcome,
50616
+ answers
50617
+ });
50280
50618
  }
50281
50619
  async #resolveDesktopQuestion(interactionId, thread) {
50282
50620
  for (const [requestId2, pending] of this.#pendingDesktopQuestions) {
@@ -50284,7 +50622,7 @@ var AppServerHost = class {
50284
50622
  continue;
50285
50623
  if (pending.timeout) clearTimeout(pending.timeout);
50286
50624
  this.#pendingDesktopQuestions.delete(requestId2);
50287
- if (pending.extended) continue;
50625
+ if (pending.extended && !pending.desktopNotified) continue;
50288
50626
  await this.#writer.json({
50289
50627
  method: "serverRequest/resolved",
50290
50628
  params: { threadId: pending.thread.id, requestId: requestId2 }
@@ -50299,6 +50637,18 @@ var AppServerHost = class {
50299
50637
  this.#nextQuestionRequestId -= 1;
50300
50638
  return requestId2;
50301
50639
  }
50640
+ #scheduleQuestionTimeout(requestId2, pending) {
50641
+ if (pending.timeout) {
50642
+ clearTimeout(pending.timeout);
50643
+ pending.timeout = null;
50644
+ }
50645
+ const expiresAtMs = pending.interaction.expiresAt ? Date.parse(pending.interaction.expiresAt) : Number.NaN;
50646
+ const timeoutMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - Date.now()) : null;
50647
+ if (timeoutMs === null) return;
50648
+ pending.timeout = setTimeout(() => {
50649
+ void this.#cancelExpiredQuestion(requestId2).catch((error51) => this.#diagnose(error51));
50650
+ }, timeoutMs);
50651
+ }
50302
50652
  async #setThreadStatus(thread, status2) {
50303
50653
  thread.thread.status = status2;
50304
50654
  await this.#writer.json({