@alook/daemon 0.1.76 → 0.1.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -42819,7 +42819,7 @@ var ExternalSendRequestSchema = exports_external.strictObject({
42819
42819
  text: exports_external.string().trim().max(BOT_IM_EXTERNAL_SEND_MAX_BYTES).optional().default(""),
42820
42820
  attachments: exports_external.array(exports_external.string().trim().min(1).max(128)).max(BOT_IM_MAX_ATTACHMENTS).optional()
42821
42821
  }).refine((value) => value.text.length > 0 || (value.attachments?.length ?? 0) > 0, {
42822
- message: "Either text or at least one attachment is required"
42822
+ error: "Either text or at least one attachment is required"
42823
42823
  });
42824
42824
  var ExternalSendResponseSchema = exports_external.strictObject({
42825
42825
  state: exports_external.literal("sent"),
@@ -42904,7 +42904,7 @@ var DiagnosticCollectCommandSchema = exports_external.object({
42904
42904
  agentId: AgentIdSchema,
42905
42905
  fromMs: SafeEpochSchema,
42906
42906
  deadlineAt: SafeEpochSchema
42907
- }).strict().refine((command) => command.deadlineAt - command.fromMs === DIAGNOSTIC_COLLECT_SPAN_MS, { message: "diagnostic collection span must match v1" });
42907
+ }).strict().refine((command) => command.deadlineAt - command.fromMs === DIAGNOSTIC_COLLECT_SPAN_MS, { error: "diagnostic collection span must match v1" });
42908
42908
  var OwnerDiagnosticReportBase = {
42909
42909
  reportId: DiagnosticReportIdSchema,
42910
42910
  deadlineAt: SafeEpochSchema
@@ -43140,7 +43140,7 @@ var AutomationPermissionPolicySchema = exports_external.strictObject({
43140
43140
  limit: exports_external.number().int().positive(),
43141
43141
  period: exports_external.enum(["hour", "day"])
43142
43142
  }).refine((value) => value.limit <= AUTOMATION_PERMISSION_LIMITS[value.period], {
43143
- message: `Limit cannot exceed ${AUTOMATION_PERMISSION_LIMITS.hour}/hour or ${AUTOMATION_PERMISSION_LIMITS.day}/day`,
43143
+ error: `Limit cannot exceed ${AUTOMATION_PERMISSION_LIMITS.hour}/hour or ${AUTOMATION_PERMISSION_LIMITS.day}/day`,
43144
43144
  path: ["limit"]
43145
43145
  });
43146
43146
  var permissions = exports_external.array(AutomationPermissionPolicySchema).min(1).max(AutomationPermissionSchema.options.length).refine((values) => new Set(values.map((value) => value.permission)).size === values.length, "Duplicate permission");
@@ -43228,6 +43228,12 @@ var FriendApprovalPayloadSchema = exports_external.strictObject({
43228
43228
 
43229
43229
  // ../shared/src/community/bot-model.ts
43230
43230
  var BOT_MODEL_NAME_MAX_LENGTH = 100;
43231
+ function resolveModelConfig(modelName) {
43232
+ const name = (modelName ?? "").trim();
43233
+ if (name.length === 0)
43234
+ return { kind: "default" };
43235
+ return { kind: "named", name };
43236
+ }
43231
43237
 
43232
43238
  // ../shared/src/model-observation.ts
43233
43239
  var identity2 = exports_external.string().min(1).max(256).regex(/^[^\s\u0000-\u001f\u007f]+$/);
@@ -43284,7 +43290,7 @@ var DecisionCardQuestionInputSchema = exports_external.strictObject({
43284
43290
  function hasDuplicateIds(ids) {
43285
43291
  return new Set(ids).size !== ids.length;
43286
43292
  }
43287
- var mentionHandleSchema = exports_external.string().trim().min(1).max(128).refine((value) => parseNameAndTag(value.startsWith("@") ? value.slice(1) : value) !== null, { message: 'mention must be a handle like "@alice#0001"' });
43293
+ var mentionHandleSchema = exports_external.string().trim().min(1).max(128).refine((value) => parseNameAndTag(value.startsWith("@") ? value.slice(1) : value) !== null, { error: 'mention must be a handle like "@alice#0001"' });
43288
43294
  var DecisionCardInputSchema = exports_external.strictObject({
43289
43295
  mentions: exports_external.array(mentionHandleSchema).max(DECISION_CARD_MAX_MENTIONS).optional(),
43290
43296
  summary: requiredSummarySchema,
@@ -43406,7 +43412,7 @@ function tokenUsageCapability(backendId) {
43406
43412
  return tokenUsageBackends.has(backendId) ? "supported" : backendId === "cursor" ? "unsupported" : "unknown";
43407
43413
  }
43408
43414
  var safeToken = exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
43409
- var boundedText = exports_external.string().min(1).refine((value) => new TextEncoder().encode(value).length <= 64, { message: "must be at most 64 UTF-8 bytes" });
43415
+ var boundedText = exports_external.string().min(1).refine((value) => new TextEncoder().encode(value).length <= 64, { error: "must be at most 64 UTF-8 bytes" });
43410
43416
  var DailyUsageMetricSchema = safeToken.nullable();
43411
43417
  var DailyUsageSnapshotSchema = exports_external.object({
43412
43418
  botId: exports_external.string().min(1),
@@ -43492,7 +43498,7 @@ var ProviderQuotaSnapshotSchema = exports_external.object({
43492
43498
  agentBackendId: ProviderQuotaBackendSchema,
43493
43499
  observation: ProviderQuotaObservationSchema
43494
43500
  }).strict();
43495
- var ProviderQuotaSnapshotListSchema = exports_external.array(ProviderQuotaSnapshotSchema).refine((snapshots) => new Set(snapshots.map((snapshot) => snapshot.agentBackendId)).size === snapshots.length, { message: "duplicate provider quota backend" });
43501
+ var ProviderQuotaSnapshotListSchema = exports_external.array(ProviderQuotaSnapshotSchema).refine((snapshots) => new Set(snapshots.map((snapshot) => snapshot.agentBackendId)).size === snapshots.length, { error: "duplicate provider quota backend" });
43496
43502
 
43497
43503
  // ../shared/src/constants.ts
43498
43504
  var COMMUNITY_MACHINE_HEARTBEAT_MS = 30000;
@@ -43751,10 +43757,10 @@ var isMentionSafeName = (name) => validateCommunityName(name).ok;
43751
43757
  var MENTION_SAFE_NAME_MSG = "name cannot contain #, @, or line breaks";
43752
43758
  var BOT_AVATAR_ROUTE_PATTERN = /^\/api\/community\/bots\/[A-Za-z0-9_-]+\/avatar$/;
43753
43759
  var BotImageUrlSchema = exports_external.string().max(COMMUNITY_BOT_IMAGE_URL_MAX).refine((v) => v.startsWith("https://") || v.startsWith("avatar:") || BOT_AVATAR_ROUTE_PATTERN.test(v), {
43754
- message: "image must be an https URL, the bot avatar route, or an avatar: config"
43760
+ error: "image must be an https URL, the bot avatar route, or an avatar: config"
43755
43761
  });
43756
43762
  var CommunityBotCreateRequestSchema = exports_external.object({
43757
- name: exports_external.string().trim().min(COMMUNITY_BOT_NAME_MIN).max(COMMUNITY_BOT_NAME_MAX).refine(isMentionSafeName, { message: MENTION_SAFE_NAME_MSG }),
43763
+ name: exports_external.string().trim().min(COMMUNITY_BOT_NAME_MIN).max(COMMUNITY_BOT_NAME_MAX).refine(isMentionSafeName, { error: MENTION_SAFE_NAME_MSG }),
43758
43764
  description: exports_external.string().max(COMMUNITY_BOT_DESCRIPTION_MAX).optional(),
43759
43765
  machineId: exports_external.string().min(1),
43760
43766
  runtime: exports_external.string().min(1),
@@ -43763,14 +43769,14 @@ var CommunityBotCreateRequestSchema = exports_external.object({
43763
43769
  reasoningEffort: ReasoningEffortSchema.nullable().optional()
43764
43770
  });
43765
43771
  var CommunityBotPatchRequestSchema = exports_external.object({
43766
- name: exports_external.string().trim().min(COMMUNITY_BOT_NAME_MIN).max(COMMUNITY_BOT_NAME_MAX).refine(isMentionSafeName, { message: MENTION_SAFE_NAME_MSG }).optional(),
43772
+ name: exports_external.string().trim().min(COMMUNITY_BOT_NAME_MIN).max(COMMUNITY_BOT_NAME_MAX).refine(isMentionSafeName, { error: MENTION_SAFE_NAME_MSG }).optional(),
43767
43773
  description: exports_external.string().max(COMMUNITY_BOT_DESCRIPTION_MAX).optional(),
43768
43774
  image: BotImageUrlSchema.nullable().optional(),
43769
43775
  model: exports_external.string().trim().min(1).max(BOT_MODEL_NAME_MAX_LENGTH).nullable().optional(),
43770
43776
  runtime: exports_external.string().trim().min(1).max(COMMUNITY_RUNTIME_ID_MAX).optional(),
43771
43777
  reasoningEffort: ReasoningEffortSchema.nullable().optional()
43772
43778
  }).refine((v) => v.name !== undefined || v.description !== undefined || v.image !== undefined || v.runtime !== undefined || ("reasoningEffort" in v) || ("model" in v), {
43773
- message: "at least one field must be provided"
43779
+ error: "at least one field must be provided"
43774
43780
  });
43775
43781
  var CommunityBotAddToServerRequestSchema = exports_external.object({
43776
43782
  botId: exports_external.string().min(1)
@@ -43788,7 +43794,7 @@ var CommunityServerOnboardRequestSchema = exports_external.strictObject({
43788
43794
  }),
43789
43795
  exports_external.strictObject({ type: exports_external.literal("finalize") })
43790
43796
  ])
43791
- }).refine(({ bots, leadBotId }) => bots.some((bot) => bot.id === leadBotId), { message: "leadBotId must reference an onboarded bot", path: ["leadBotId"] }).refine(({ bots, action }) => action.type !== "wake" || bots.some((bot) => bot.id === action.botId), { message: "wake botId must reference an onboarded bot", path: ["action", "botId"] });
43797
+ }).refine(({ bots, leadBotId }) => bots.some((bot) => bot.id === leadBotId), { error: "leadBotId must reference an onboarded bot", path: ["leadBotId"] }).refine(({ bots, action }) => action.type !== "wake" || bots.some((bot) => bot.id === action.botId), { error: "wake botId must reference an onboarded bot", path: ["action", "botId"] });
43792
43798
  var CommunityAgentMessageContentSchema = exports_external.object({ text: exports_external.string().max(MAX_MESSAGE_CONTENT_LENGTH).default("") }).catchall(exports_external.unknown());
43793
43799
  var CommunityAgentSeqSchema = exports_external.number().int().min(0);
43794
43800
  var CommunityAgentPositiveSeqSchema = exports_external.number().int().min(1);
@@ -43853,7 +43859,7 @@ var CommunityAgentUpdateProfileRequestSchema = exports_external.object({
43853
43859
  data: exports_external.instanceof(Uint8Array).refine((value) => value.byteLength > 0, "avatar must not be empty").refine((value) => value.byteLength <= MAX_SERVER_ICON_SIZE_BYTES, `avatar must be ≤ ${MAX_SERVER_ICON_SIZE_BYTES} bytes`)
43854
43860
  }).optional()
43855
43861
  }).refine((value) => value.bio !== undefined || value.avatar !== undefined, {
43856
- message: "bio or avatar is required"
43862
+ error: "bio or avatar is required"
43857
43863
  });
43858
43864
  var CommunityAgentInboxPullRequestSchema = exports_external.object({
43859
43865
  max: exports_external.number().int().min(1).max(200).optional()
@@ -43867,7 +43873,7 @@ var CommunityAgentReadRequestSchema = exports_external.object({
43867
43873
  after: CommunityAgentSeqSchema.optional(),
43868
43874
  around: CommunityAgentSeqSchema.optional(),
43869
43875
  limit: exports_external.number().int().min(1).max(200).optional()
43870
- }).refine((v) => [v.before, v.after, v.around].filter((x) => x !== undefined).length <= 1, { message: "at most one of before/after/around may be supplied" });
43876
+ }).refine((v) => [v.before, v.after, v.around].filter((x) => x !== undefined).length <= 1, { error: "at most one of before/after/around may be supplied" });
43871
43877
  var CommunityAgentResolveRequestSchema = exports_external.object({
43872
43878
  channel: exports_external.string().min(1),
43873
43879
  seq: CommunityAgentSeqSchema
@@ -43889,7 +43895,7 @@ var CommunityAgentJoinServerRequestSchema = exports_external.object({
43889
43895
  });
43890
43896
  var CommunityAgentNapRequestSchema = exports_external.object({
43891
43897
  handoff: exports_external.string().refine((value) => value.trim().length > 0, {
43892
- message: "handoff must not be blank"
43898
+ error: "handoff must not be blank"
43893
43899
  }).optional()
43894
43900
  });
43895
43901
  var CommunityAgentMessagePropertyRequestSchema = exports_external.object({
@@ -43915,7 +43921,7 @@ var AuditLogThinkingPayloadSchema = exports_external.object({
43915
43921
  chars: exports_external.number().int().nonnegative()
43916
43922
  });
43917
43923
  var AuditLogTextPayloadSchema = exports_external.object({
43918
- text: exports_external.string().min(1).max(BOT_AUDIT_TEXT_MAX_BYTES).refine((text) => new TextEncoder().encode(text).byteLength <= BOT_AUDIT_TEXT_MAX_BYTES, { message: "Text exceeds 1024 UTF-8 bytes" }),
43924
+ text: exports_external.string().min(1).max(BOT_AUDIT_TEXT_MAX_BYTES).refine((text) => new TextEncoder().encode(text).byteLength <= BOT_AUDIT_TEXT_MAX_BYTES, { error: "Text exceeds 1024 UTF-8 bytes" }),
43919
43925
  truncated: exports_external.boolean(),
43920
43926
  chars: exports_external.number().int().nonnegative()
43921
43927
  });
@@ -44174,7 +44180,7 @@ var CommunityMessageResourceSchema = exports_external.strictObject({
44174
44180
  authorId: id.optional(),
44175
44181
  authorName: exports_external.string(),
44176
44182
  deleted: exports_external.boolean().optional()
44177
- }).refine((reply) => reply.deleted === true || reply.authorId !== undefined, { message: "Live reply author identity missing" }).optional(),
44183
+ }).refine((reply) => reply.deleted === true || reply.authorId !== undefined, { error: "Live reply author identity missing" }).optional(),
44178
44184
  embeds: exports_external.array(exports_external.unknown()).optional(),
44179
44185
  reactions: exports_external.array(exports_external.strictObject({
44180
44186
  emoji: exports_external.string(),
@@ -44707,7 +44713,7 @@ function makeRuntimeConfig(input2) {
44707
44713
  instruction: input2.instruction
44708
44714
  };
44709
44715
  }
44710
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/entity.js
44716
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/entity.js
44711
44717
  var entityKind = Symbol.for("drizzle:entityKind");
44712
44718
  var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
44713
44719
  function is(value, type) {
@@ -44732,7 +44738,7 @@ function is(value, type) {
44732
44738
  return false;
44733
44739
  }
44734
44740
 
44735
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/column.js
44741
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/column.js
44736
44742
  class Column {
44737
44743
  constructor(table, config2) {
44738
44744
  this.table = table;
@@ -44782,7 +44788,7 @@ class Column {
44782
44788
  }
44783
44789
  }
44784
44790
 
44785
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/column-builder.js
44791
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/column-builder.js
44786
44792
  class ColumnBuilder {
44787
44793
  static [entityKind] = "ColumnBuilder";
44788
44794
  config;
@@ -44838,20 +44844,20 @@ class ColumnBuilder {
44838
44844
  }
44839
44845
  }
44840
44846
 
44841
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.utils.js
44847
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/table.utils.js
44842
44848
  var TableName = Symbol.for("drizzle:Name");
44843
44849
 
44844
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing-utils.js
44850
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/tracing-utils.js
44845
44851
  function iife(fn, ...args) {
44846
44852
  return fn(...args);
44847
44853
  }
44848
44854
 
44849
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/unique-constraint.js
44855
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/pg-core/unique-constraint.js
44850
44856
  function uniqueKeyName(table, columns) {
44851
44857
  return `${table[TableName]}_${columns.join("_")}_unique`;
44852
44858
  }
44853
44859
 
44854
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/columns/common.js
44860
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/pg-core/columns/common.js
44855
44861
  class PgColumn extends Column {
44856
44862
  constructor(table, config2) {
44857
44863
  if (!config2.uniqueName) {
@@ -44900,7 +44906,7 @@ class ExtraConfigColumn extends PgColumn {
44900
44906
  }
44901
44907
  }
44902
44908
 
44903
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/pg-core/columns/enum.js
44909
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/pg-core/columns/enum.js
44904
44910
  class PgEnumObjectColumn extends PgColumn {
44905
44911
  static [entityKind] = "PgEnumObjectColumn";
44906
44912
  enum;
@@ -44930,7 +44936,7 @@ class PgEnumColumn extends PgColumn {
44930
44936
  }
44931
44937
  }
44932
44938
 
44933
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/subquery.js
44939
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/subquery.js
44934
44940
  class Subquery {
44935
44941
  static [entityKind] = "Subquery";
44936
44942
  constructor(sql, fields, alias, isWith = false, usedTables = []) {
@@ -44945,10 +44951,10 @@ class Subquery {
44945
44951
  }
44946
44952
  }
44947
44953
 
44948
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/version.js
44954
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/version.js
44949
44955
  var version2 = "0.45.4";
44950
44956
 
44951
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/tracing.js
44957
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/tracing.js
44952
44958
  var otel;
44953
44959
  var rawTracer;
44954
44960
  var tracer = {
@@ -44975,10 +44981,10 @@ var tracer = {
44975
44981
  }
44976
44982
  };
44977
44983
 
44978
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/view-common.js
44984
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/view-common.js
44979
44985
  var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
44980
44986
 
44981
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/table.js
44987
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/table.js
44982
44988
  var Schema = Symbol.for("drizzle:Schema");
44983
44989
  var Columns = Symbol.for("drizzle:Columns");
44984
44990
  var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
@@ -45016,7 +45022,7 @@ class Table {
45016
45022
  }
45017
45023
  }
45018
45024
 
45019
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/sql.js
45025
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sql/sql.js
45020
45026
  function isSQLWrapper(value) {
45021
45027
  return value !== null && value !== undefined && typeof value.getSQL === "function";
45022
45028
  }
@@ -45379,7 +45385,7 @@ Subquery.prototype.getSQL = function() {
45379
45385
  return new SQL([this]);
45380
45386
  };
45381
45387
 
45382
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/alias.js
45388
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/alias.js
45383
45389
  class ColumnAliasProxyHandler {
45384
45390
  constructor(table) {
45385
45391
  this.table = table;
@@ -45435,7 +45441,7 @@ class TableAliasProxyHandler {
45435
45441
  }
45436
45442
  }
45437
45443
 
45438
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/utils.js
45444
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/utils.js
45439
45445
  function getColumnNameAndConfig(a, b) {
45440
45446
  return {
45441
45447
  name: typeof a === "string" && a.length > 0 ? a : "",
@@ -45444,7 +45450,7 @@ function getColumnNameAndConfig(a, b) {
45444
45450
  }
45445
45451
  var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
45446
45452
 
45447
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/expressions/conditions.js
45453
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sql/expressions/conditions.js
45448
45454
  function bindIfParam(value, column) {
45449
45455
  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
45450
45456
  return new Param(value, column);
@@ -45475,7 +45481,7 @@ function isNotNull(value) {
45475
45481
  return sql`${value} is not null`;
45476
45482
  }
45477
45483
 
45478
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sql/expressions/select.js
45484
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sql/expressions/select.js
45479
45485
  function desc(column) {
45480
45486
  return sql`${column} desc`;
45481
45487
  }
@@ -45512,12 +45518,12 @@ __export(exports_community_schema, {
45512
45518
  communityAttachment: () => communityAttachment
45513
45519
  });
45514
45520
 
45515
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/alias.js
45521
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/alias.js
45516
45522
  function alias(table, alias2) {
45517
45523
  return new Proxy(table, new TableAliasProxyHandler(alias2, false));
45518
45524
  }
45519
45525
 
45520
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/checks.js
45526
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/checks.js
45521
45527
  class CheckBuilder {
45522
45528
  constructor(name, value) {
45523
45529
  this.name = name;
@@ -45544,7 +45550,7 @@ function check2(name, value) {
45544
45550
  return new CheckBuilder(name, value);
45545
45551
  }
45546
45552
 
45547
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
45553
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
45548
45554
  class ForeignKeyBuilder {
45549
45555
  static [entityKind] = "SQLiteForeignKeyBuilder";
45550
45556
  reference;
@@ -45598,7 +45604,7 @@ class ForeignKey {
45598
45604
  }
45599
45605
  }
45600
45606
 
45601
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
45607
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
45602
45608
  function uniqueKeyName2(table, columns) {
45603
45609
  return `${table[TableName]}_${columns.join("_")}_unique`;
45604
45610
  }
@@ -45643,7 +45649,7 @@ class UniqueConstraint {
45643
45649
  }
45644
45650
  }
45645
45651
 
45646
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/common.js
45652
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/common.js
45647
45653
  class SQLiteColumnBuilder extends ColumnBuilder {
45648
45654
  static [entityKind] = "SQLiteColumnBuilder";
45649
45655
  foreignKeyConfigs = [];
@@ -45694,7 +45700,7 @@ class SQLiteColumn extends Column {
45694
45700
  static [entityKind] = "SQLiteColumn";
45695
45701
  }
45696
45702
 
45697
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/blob.js
45703
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/blob.js
45698
45704
  class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
45699
45705
  static [entityKind] = "SQLiteBigIntBuilder";
45700
45706
  constructor(name) {
@@ -45782,7 +45788,7 @@ function blob(a, b) {
45782
45788
  return new SQLiteBlobBufferBuilder(name);
45783
45789
  }
45784
45790
 
45785
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/custom.js
45791
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/custom.js
45786
45792
  class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
45787
45793
  static [entityKind] = "SQLiteCustomColumnBuilder";
45788
45794
  constructor(name, fieldConfig, customTypeParams) {
@@ -45823,7 +45829,7 @@ function customType(customTypeParams) {
45823
45829
  };
45824
45830
  }
45825
45831
 
45826
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/integer.js
45832
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/integer.js
45827
45833
  class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
45828
45834
  static [entityKind] = "SQLiteBaseIntegerBuilder";
45829
45835
  constructor(name, dataType, columnType) {
@@ -45925,7 +45931,7 @@ function integer2(a, b) {
45925
45931
  return new SQLiteIntegerBuilder(name);
45926
45932
  }
45927
45933
 
45928
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
45934
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
45929
45935
  class SQLiteNumericBuilder extends SQLiteColumnBuilder {
45930
45936
  static [entityKind] = "SQLiteNumericBuilder";
45931
45937
  constructor(name) {
@@ -45995,7 +46001,7 @@ function numeric(a, b) {
45995
46001
  return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
45996
46002
  }
45997
46003
 
45998
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/real.js
46004
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/real.js
45999
46005
  class SQLiteRealBuilder extends SQLiteColumnBuilder {
46000
46006
  static [entityKind] = "SQLiteRealBuilder";
46001
46007
  constructor(name) {
@@ -46016,7 +46022,7 @@ function real(name) {
46016
46022
  return new SQLiteRealBuilder(name ?? "");
46017
46023
  }
46018
46024
 
46019
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/text.js
46025
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/text.js
46020
46026
  class SQLiteTextBuilder extends SQLiteColumnBuilder {
46021
46027
  static [entityKind] = "SQLiteTextBuilder";
46022
46028
  constructor(name, config2) {
@@ -46071,7 +46077,7 @@ function text(a, b = {}) {
46071
46077
  return new SQLiteTextBuilder(name, config2);
46072
46078
  }
46073
46079
 
46074
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/columns/all.js
46080
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/columns/all.js
46075
46081
  function getSQLiteColumnBuilders() {
46076
46082
  return {
46077
46083
  blob,
@@ -46083,7 +46089,7 @@ function getSQLiteColumnBuilders() {
46083
46089
  };
46084
46090
  }
46085
46091
 
46086
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/table.js
46092
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/table.js
46087
46093
  var InlineForeignKeys = Symbol.for("drizzle:SQLiteInlineForeignKeys");
46088
46094
 
46089
46095
  class SQLiteTable extends Table {
@@ -46117,7 +46123,7 @@ var sqliteTable = (name, columns, extraConfig) => {
46117
46123
  return sqliteTableBase(name, columns, extraConfig);
46118
46124
  };
46119
46125
 
46120
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/indexes.js
46126
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/indexes.js
46121
46127
  class IndexBuilderOn {
46122
46128
  constructor(name, unique2) {
46123
46129
  this.name = name;
@@ -46163,7 +46169,7 @@ function uniqueIndex(name) {
46163
46169
  return new IndexBuilderOn(name, true);
46164
46170
  }
46165
46171
 
46166
- // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261119.1_@opentelemetry+api@1.10.0_@ty_38fec08cb14afcae8326bba90a769ca2/node_modules/drizzle-orm/sqlite-core/primary-keys.js
46172
+ // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261125.1_@opentelemetry+api@1.10.0_@ty_fa28369ca622e5aaa983ff44c7d551d0/node_modules/drizzle-orm/sqlite-core/primary-keys.js
46167
46173
  function primaryKey(...config2) {
46168
46174
  if (config2[0].columns) {
46169
46175
  return new PrimaryKeyBuilder(config2[0].columns, config2[0].name);
@@ -47260,7 +47266,7 @@ var communityChannelDeleteSchema = exports_external.strictObject({
47260
47266
  channelId: string4,
47261
47267
  parentChannelId: nullableString.optional(),
47262
47268
  parentMessageId: string4.optional()
47263
- }).refine((event) => event.parentMessageId === undefined || typeof event.parentChannelId === "string" && event.parentChannelId.length > 0, { message: "parentMessageId requires parentChannelId" });
47269
+ }).refine((event) => event.parentMessageId === undefined || typeof event.parentChannelId === "string" && event.parentChannelId.length > 0, { error: "parentMessageId requires parentChannelId" });
47264
47270
  var positionedIdSchema = exports_external.strictObject({ id: string4, position: exports_external.number() });
47265
47271
  var communityChannelReorderSchema = exports_external.strictObject({
47266
47272
  type: exports_external.literal("community:channel.reorder"),
@@ -47875,6 +47881,7 @@ var communityScheduleRun = sqliteTable("community_schedule_run", {
47875
47881
  status: text("status").$type().notNull(),
47876
47882
  lastError: text("last_error"),
47877
47883
  ackedAtMs: integer2("acked_at_ms"),
47884
+ ackResult: text("ack_result"),
47878
47885
  createdAtMs: integer2("created_at_ms").notNull(),
47879
47886
  updatedAtMs: integer2("updated_at_ms").notNull()
47880
47887
  }, (t) => [
@@ -47993,6 +48000,10 @@ var viewerTicket = exports_external.strictObject({ userId: exports_external.stri
47993
48000
  // ../shared/src/schedule.ts
47994
48001
  var SCHEDULE_TITLE_MAX_LENGTH = 160;
47995
48002
  var SCHEDULE_DESCRIPTION_MAX_LENGTH = 4000;
48003
+ var SCHEDULE_ACK_RESULT_MAX_BYTES = 1024;
48004
+ function utf8ByteLength2(value) {
48005
+ return new TextEncoder().encode(value).byteLength;
48006
+ }
47996
48007
  var SCHEDULE_MIN_DURATION_MINUTES = 5;
47997
48008
  var SCHEDULE_MAX_DURATION_MINUTES = 1440;
47998
48009
  var SCHEDULE_MAX_RANGE_MS = 62 * 24 * 60 * 60 * 1000;
@@ -48042,6 +48053,7 @@ var ScheduleLastExecutionSchema = exports_external.strictObject({
48042
48053
  status: ScheduleRunStatusSchema,
48043
48054
  lastError: exports_external.string().nullable(),
48044
48055
  ackedAt: exports_external.iso.datetime().nullable(),
48056
+ ackResult: exports_external.string().nullable().optional(),
48045
48057
  updatedAt: exports_external.iso.datetime()
48046
48058
  });
48047
48059
  var ScheduleSourceMessageSchema = exports_external.strictObject({
@@ -48073,7 +48085,9 @@ var ScheduleOccurrenceSchema = exports_external.strictObject({
48073
48085
  occurrenceKey: exports_external.string().min(1),
48074
48086
  startAt: exports_external.iso.datetime(),
48075
48087
  endAt: exports_external.iso.datetime(),
48076
- runStatus: ScheduleOccurrenceStatusSchema
48088
+ runStatus: ScheduleOccurrenceStatusSchema,
48089
+ ackedAt: exports_external.iso.datetime().nullable().optional(),
48090
+ ackResult: exports_external.string().nullable().optional()
48077
48091
  });
48078
48092
  var ScheduleListResponseSchema = exports_external.strictObject({
48079
48093
  events: exports_external.array(ScheduleEventSchema),
@@ -48089,6 +48103,7 @@ var ScheduleCreateRequestSchema = exports_external.strictObject({
48089
48103
  recurrence: ScheduleRecurrenceSchema.nullable().optional(),
48090
48104
  sourceMessageRef: exports_external.string().trim().min(1).max(512)
48091
48105
  });
48106
+ var ScheduleAckResultSchema = exports_external.string().trim().min(1, "ackResult must not be empty").refine((value) => utf8ByteLength2(value) <= SCHEDULE_ACK_RESULT_MAX_BYTES, `ackResult must be at most ${SCHEDULE_ACK_RESULT_MAX_BYTES} UTF-8 bytes`);
48092
48107
  var ScheduleUpdateRequestSchema = exports_external.strictObject({
48093
48108
  title: exports_external.string().trim().min(1).max(SCHEDULE_TITLE_MAX_LENGTH).optional(),
48094
48109
  description: exports_external.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),
@@ -48097,7 +48112,16 @@ var ScheduleUpdateRequestSchema = exports_external.strictObject({
48097
48112
  timeZone: exports_external.string().trim().min(1).max(128).optional(),
48098
48113
  recurrence: ScheduleRecurrenceSchema.nullable().optional(),
48099
48114
  sourceMessageRef: exports_external.string().trim().min(1).max(512).optional(),
48100
- ack: exports_external.literal(true).optional()
48115
+ ack: exports_external.literal(true).optional(),
48116
+ ackResult: ScheduleAckResultSchema.optional()
48117
+ }).superRefine((value, ctx) => {
48118
+ if (value.ackResult !== undefined && value.ack !== true) {
48119
+ ctx.addIssue({
48120
+ code: "custom",
48121
+ path: ["ackResult"],
48122
+ message: "ackResult requires ack: true"
48123
+ });
48124
+ }
48101
48125
  });
48102
48126
  function isValidIanaTimeZone(timeZone) {
48103
48127
  if (!timeZone || typeof timeZone !== "string")
@@ -48286,7 +48310,7 @@ var BotWebhookUpdateSchema = exports_external.strictObject({
48286
48310
  allowedSenders: BotImAllowedSendersSchema.optional(),
48287
48311
  requireMentionInGroups: exports_external.boolean().optional(),
48288
48312
  regeneratePairingCode: exports_external.boolean().optional()
48289
- }).refine((v) => v.name !== undefined || v.enabled !== undefined || v.eventFilter !== undefined || v.instruction !== undefined || v.requireSecret !== undefined || v.signingSecret !== undefined || v.rotateCredentials === true || v.botToken !== undefined || v.feishuRegion !== undefined || v.feishuAppId !== undefined || v.feishuAppSecret !== undefined || v.feishuVerificationToken !== undefined || v.feishuEncryptKey !== undefined || v.accessPolicy !== undefined || v.allowedSenders !== undefined || v.requireMentionInGroups !== undefined || v.regeneratePairingCode === true, { message: "At least one field must be provided" });
48313
+ }).refine((v) => v.name !== undefined || v.enabled !== undefined || v.eventFilter !== undefined || v.instruction !== undefined || v.requireSecret !== undefined || v.signingSecret !== undefined || v.rotateCredentials === true || v.botToken !== undefined || v.feishuRegion !== undefined || v.feishuAppId !== undefined || v.feishuAppSecret !== undefined || v.feishuVerificationToken !== undefined || v.feishuEncryptKey !== undefined || v.accessPolicy !== undefined || v.allowedSenders !== undefined || v.requireMentionInGroups !== undefined || v.regeneratePairingCode === true, { error: "At least one field must be provided" });
48290
48314
  var BotWebhookCreateResponseSchema = exports_external.strictObject({
48291
48315
  webhook: BotWebhookSummarySchema,
48292
48316
  webhookUrl: exports_external.url().optional(),
@@ -66221,6 +66245,8 @@ class SettledUsageProjector {
66221
66245
  // agent-driver/dist/adapters/agy/acp-lane.js
66222
66246
  var ACP_PROTOCOL_VERSION = 1;
66223
66247
  var HANDSHAKE_TIMEOUT_MS = 15000;
66248
+ var POST_TURN_ACTIVITY_SETTLE_MS = 5000;
66249
+ var SESSION_PROGRESS_HEARTBEAT_MIN_INTERVAL_MS = 1000;
66224
66250
  var PROMPT_STOP_REASONS = new Set([
66225
66251
  "end_turn",
66226
66252
  "max_tokens",
@@ -66293,6 +66319,8 @@ class AgyAcpLane {
66293
66319
  toolCalls = new Map;
66294
66320
  completedTools = new Set;
66295
66321
  unownedContent = false;
66322
+ postTurnSettleUntil = null;
66323
+ lastSessionProgressAt = null;
66296
66324
  activityReader;
66297
66325
  activityRead;
66298
66326
  activityTimer;
@@ -66434,6 +66462,8 @@ class AgyAcpLane {
66434
66462
  this.ready = false;
66435
66463
  this.clearActivityTimer();
66436
66464
  this.childProgressBaseline = null;
66465
+ this.postTurnSettleUntil = null;
66466
+ this.lastSessionProgressAt = null;
66437
66467
  this.currentPromptRequestId = null;
66438
66468
  this.terminalOwner = null;
66439
66469
  this.toolCalls.clear();
@@ -66760,6 +66790,10 @@ class AgyAcpLane {
66760
66790
  }
66761
66791
  throw error62;
66762
66792
  }
66793
+ if (delivery === "prompt") {
66794
+ this.postTurnSettleUntil = null;
66795
+ this.lastSessionProgressAt = null;
66796
+ }
66763
66797
  return { ok: true, acceptedAs: delivery, receipt: prompt.receipt };
66764
66798
  }
66765
66799
  completePrompt(prompt, value) {
@@ -66813,7 +66847,8 @@ class AgyAcpLane {
66813
66847
  if (this.terminalOwner !== owner || this.requestedStopReason || this.processTerminal)
66814
66848
  return;
66815
66849
  if (this.hasPendingTools())
66816
- this.unownedContent = true;
66850
+ this.markUnownedContent();
66851
+ this.postTurnSettleUntil = !this.hasPendingTools() && !this.unownedContent ? this.now() + (this.options.postTurnActivitySettleMs ?? POST_TURN_ACTIVITY_SETTLE_MS) : null;
66817
66852
  this.observeOutsideWork();
66818
66853
  this.refreshActivity();
66819
66854
  this.finishing = false;
@@ -66849,6 +66884,7 @@ class AgyAcpLane {
66849
66884
  this.currentPromptRequestId = null;
66850
66885
  this.terminalOwner = null;
66851
66886
  this.contentOwner = undefined;
66887
+ this.lastSessionProgressAt = null;
66852
66888
  this.promptOutcomes.clear();
66853
66889
  this.observedPrompts.clear();
66854
66890
  if (!latest) {
@@ -66953,6 +66989,8 @@ class AgyAcpLane {
66953
66989
  this.processTerminal = true;
66954
66990
  this.ready = false;
66955
66991
  this.clearActivityTimer();
66992
+ this.postTurnSettleUntil = null;
66993
+ this.lastSessionProgressAt = null;
66956
66994
  this.rejectConfigWaiter(normalized);
66957
66995
  this.currentPromptRequestId = null;
66958
66996
  this.terminalOwner = null;
@@ -66974,6 +67012,8 @@ class AgyAcpLane {
66974
67012
  this.processTerminal = true;
66975
67013
  this.ready = false;
66976
67014
  this.clearActivityTimer();
67015
+ this.postTurnSettleUntil = null;
67016
+ this.lastSessionProgressAt = null;
66977
67017
  const exitError = new Error("Agy ACP process exited");
66978
67018
  this.rejectConfigWaiter(exitError);
66979
67019
  this.currentPromptRequestId = null;
@@ -67071,7 +67111,7 @@ class AgyAcpLane {
67071
67111
  return;
67072
67112
  }
67073
67113
  if (this.currentPromptRequestId === null) {
67074
- this.unownedContent = true;
67114
+ this.markUnownedContent();
67075
67115
  this.observeOutsideWork();
67076
67116
  }
67077
67117
  this.write({
@@ -67109,14 +67149,17 @@ class AgyAcpLane {
67109
67149
  case "agent_message_chunk": {
67110
67150
  const content3 = record3(update.content);
67111
67151
  if (content3?.type === "text" && typeof content3.text === "string") {
67112
- if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
67113
- this.unownedContent = true;
67152
+ const sessionScoped = this.isSessionScopedEvent(this.contentOwner);
67153
+ if (sessionScoped) {
67154
+ this.markUnownedContent();
67114
67155
  this.observeOutsideWork();
67156
+ if (content3.text.length > 0)
67157
+ this.emitSessionProgress("session_message");
67115
67158
  }
67116
67159
  this.events.emit("runtime_event", {
67117
67160
  kind: "assistant_message_delta",
67118
67161
  text: content3.text,
67119
- ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
67162
+ ...sessionScoped ? { attribution: { scope: "session" } } : {}
67120
67163
  });
67121
67164
  }
67122
67165
  return;
@@ -67124,14 +67167,17 @@ class AgyAcpLane {
67124
67167
  case "agent_thought_chunk": {
67125
67168
  const content3 = record3(update.content);
67126
67169
  if (content3?.type === "text" && typeof content3.text === "string") {
67127
- if (!this.contentOwner || this.contentOwner !== this.terminalOwner) {
67128
- this.unownedContent = true;
67170
+ const sessionScoped = this.isSessionScopedEvent(this.contentOwner);
67171
+ if (sessionScoped) {
67172
+ this.markUnownedContent();
67129
67173
  this.observeOutsideWork();
67174
+ if (content3.text.length > 0)
67175
+ this.emitSessionProgress("session_reasoning");
67130
67176
  }
67131
67177
  this.events.emit("runtime_event", {
67132
67178
  kind: "assistant_reasoning_delta",
67133
67179
  text: content3.text,
67134
- ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
67180
+ ...sessionScoped ? { attribution: { scope: "session" } } : {}
67135
67181
  });
67136
67182
  }
67137
67183
  return;
@@ -67165,13 +67211,19 @@ class AgyAcpLane {
67165
67211
  owner: this.contentOwner
67166
67212
  };
67167
67213
  this.toolCalls.set(update.toolCallId, tool);
67214
+ const sessionScoped = this.isSessionScopedEvent(tool.owner);
67215
+ if (sessionScoped)
67216
+ this.emitSessionProgress("session_tool_call");
67168
67217
  this.events.emit("runtime_event", {
67169
67218
  kind: "tool_call",
67170
67219
  callId: update.toolCallId,
67171
67220
  name: tool.name,
67172
67221
  input: update.rawInput,
67173
- ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
67222
+ ...sessionScoped ? { attribution: { scope: "session" } } : {}
67174
67223
  });
67224
+ } else if (update.status !== "completed" && update.status !== "failed") {
67225
+ if (this.isSessionScopedEvent(tool.owner))
67226
+ this.emitSessionProgress("session_tool_update");
67175
67227
  }
67176
67228
  this.observeOutsideWork();
67177
67229
  if (update.status === "completed" || update.status === "failed")
@@ -67184,18 +67236,25 @@ class AgyAcpLane {
67184
67236
  const tool = this.toolCalls.get(update.toolCallId);
67185
67237
  if (!tool)
67186
67238
  return;
67187
- if (update.status === "completed" || update.status === "failed")
67239
+ if (update.status === "completed" || update.status === "failed") {
67188
67240
  this.finishTool(update, tool);
67241
+ } else if (this.isSessionScopedEvent(tool.owner)) {
67242
+ this.emitSessionProgress("session_tool_update");
67243
+ }
67189
67244
  return;
67190
67245
  }
67191
- case "plan":
67246
+ case "plan": {
67247
+ const sessionScoped = this.isSessionScopedEvent(this.contentOwner);
67248
+ if (sessionScoped)
67249
+ this.emitSessionProgress("session_plan");
67192
67250
  this.events.emit("runtime_event", {
67193
67251
  kind: "internal_progress",
67194
67252
  source: "agy.acp",
67195
67253
  itemType: "plan",
67196
- ...!this.contentOwner || this.contentOwner !== this.terminalOwner ? { attribution: { scope: "session" } } : {}
67254
+ ...sessionScoped ? { attribution: { scope: "session" } } : {}
67197
67255
  });
67198
67256
  return;
67257
+ }
67199
67258
  default:
67200
67259
  this.diagnostic("warning", `Unsupported Agy ACP session update: ${safeLabel(updateType)}`);
67201
67260
  }
@@ -67205,8 +67264,11 @@ class AgyAcpLane {
67205
67264
  this.completedTools.add(update.toolCallId);
67206
67265
  if (this.completedTools.size > 4096)
67207
67266
  this.completedTools.delete(this.completedTools.values().next().value);
67208
- if (!tool.owner || tool.owner !== this.terminalOwner)
67209
- this.unownedContent = true;
67267
+ const sessionScoped = this.isSessionScopedEvent(tool.owner);
67268
+ if (sessionScoped) {
67269
+ this.markUnownedContent();
67270
+ this.emitSessionProgress("session_tool_output");
67271
+ }
67210
67272
  this.observeOutsideWork();
67211
67273
  this.events.emit("runtime_event", {
67212
67274
  kind: "tool_output",
@@ -67214,7 +67276,7 @@ class AgyAcpLane {
67214
67276
  name: tool.name,
67215
67277
  outcome: update.status === "failed" ? "failed" : "success",
67216
67278
  output: update.rawOutput ?? update.content,
67217
- ...tool.owner && tool.owner === this.terminalOwner ? {} : { attribution: { scope: "session" } }
67279
+ ...sessionScoped ? { attribution: { scope: "session" } } : {}
67218
67280
  });
67219
67281
  }
67220
67282
  diagnostic(severity, message) {
@@ -67225,6 +67287,33 @@ class AgyAcpLane {
67225
67287
  message
67226
67288
  });
67227
67289
  }
67290
+ now() {
67291
+ return this.options.now ? this.options.now() : Date.now();
67292
+ }
67293
+ hasActiveRootTurn() {
67294
+ return this.currentPromptRequestId !== null && this.terminalOwner !== null && !this.finishing;
67295
+ }
67296
+ isSessionScopedEvent(owner) {
67297
+ return !owner || owner !== this.terminalOwner;
67298
+ }
67299
+ markUnownedContent() {
67300
+ this.unownedContent = true;
67301
+ this.postTurnSettleUntil = null;
67302
+ }
67303
+ emitSessionProgress(itemType) {
67304
+ if (!this.hasActiveRootTurn())
67305
+ return;
67306
+ const now = this.now();
67307
+ const minIntervalMs = this.options.sessionProgressMinIntervalMs ?? SESSION_PROGRESS_HEARTBEAT_MIN_INTERVAL_MS;
67308
+ if (this.lastSessionProgressAt !== null && now - this.lastSessionProgressAt < minIntervalMs)
67309
+ return;
67310
+ this.lastSessionProgressAt = now;
67311
+ this.events.emit("runtime_event", {
67312
+ kind: "internal_progress",
67313
+ source: "agy.acp",
67314
+ itemType
67315
+ });
67316
+ }
67228
67317
  hasPendingTools() {
67229
67318
  return this.toolCalls.size > 0;
67230
67319
  }
@@ -67252,7 +67341,7 @@ class AgyAcpLane {
67252
67341
  }
67253
67342
  }
67254
67343
  observeChildProgress(children) {
67255
- if (!children || this.currentPromptRequestId === null || this.terminalOwner === null)
67344
+ if (!children || !this.hasActiveRootTurn())
67256
67345
  return;
67257
67346
  if (this.childProgressBaseline === null) {
67258
67347
  this.childProgressBaseline = toChildProgressMap(children);
@@ -67293,6 +67382,7 @@ class AgyAcpLane {
67293
67382
  if (!this.ready || !this.activityReader || this.requestedStopReason || this.processTerminal)
67294
67383
  return Promise.resolve();
67295
67384
  const revision = this.activityRevision;
67385
+ const startedWhileIdle = this.currentPromptRequestId === null;
67296
67386
  const reading = (async () => {
67297
67387
  let status = "unknown";
67298
67388
  try {
@@ -67302,10 +67392,15 @@ class AgyAcpLane {
67302
67392
  return;
67303
67393
  if (revision === this.activityRevision)
67304
67394
  this.nativeActivity = status;
67305
- if (status === "running" && this.currentPromptRequestId === null)
67306
- this.unownedContent = true;
67395
+ if (status === "idle") {
67396
+ this.postTurnSettleUntil = null;
67397
+ } else if (status === "running" && this.currentPromptRequestId === null) {
67398
+ const withinSettleWindow = !startedWhileIdle || this.postTurnSettleUntil !== null && this.now() < this.postTurnSettleUntil;
67399
+ if (!withinSettleWindow)
67400
+ this.markUnownedContent();
67401
+ }
67307
67402
  this.publishActivity();
67308
- if (this.currentPromptRequestId !== null && this.terminalOwner !== null) {
67403
+ if (this.hasActiveRootTurn()) {
67309
67404
  const children = await this.readChildProgress();
67310
67405
  if (!this.ready || this.requestedStopReason || this.processTerminal)
67311
67406
  return;
@@ -81984,161 +82079,868 @@ class ImConnectorManager {
81984
82079
  }
81985
82080
 
81986
82081
  // src/daemon/createDaemon.ts
81987
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync12 } from "node:fs";
82082
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync12, readFileSync as readFileSync13 } from "node:fs";
82083
+ import { join as join31 } from "node:path";
81988
82084
 
81989
- // src/util/rotatingFileSink.ts
81990
- import {
81991
- appendFileSync,
81992
- chmodSync as chmodSync5,
81993
- closeSync as closeSync4,
81994
- constants as constants7,
81995
- existsSync as existsSync12,
81996
- fstatSync as fstatSync2,
81997
- lstatSync as lstatSync4,
81998
- openSync as openSync4,
81999
- renameSync as renameSync5,
82000
- statSync as statSync6,
82001
- unlinkSync as unlinkSync5
82002
- } from "node:fs";
82003
- function createRotatingFileSink(path19, maxBytes, opts = {}) {
82004
- const report = (operation, error62) => {
82005
- try {
82006
- opts.onError?.({ operation, error: error62 });
82007
- } catch {}
82085
+ // src/manager/managerPolicy.ts
82086
+ function isActivelyWorking(agent) {
82087
+ return agent.status === "running" && (agent.sessionActivity?.status === "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
82088
+ }
82089
+ function sessionBlocksIdleCleanup(agent) {
82090
+ return agent.sessionActivity !== undefined && agent.sessionActivity.status !== "idle";
82091
+ }
82092
+ var DEFAULT_STALE_THRESHOLD_MS = 120000;
82093
+ var DEFAULT_TURN_SILENCE_POLICY = {
82094
+ nativeIdleTimeoutMs: 300000,
82095
+ daemonGraceMs: 60000,
82096
+ recoveryGraceMs: 60000,
82097
+ maxRecoveryExtensions: 1,
82098
+ normalBudgetMs: 360000
82099
+ };
82100
+ var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
82101
+ var DEFAULT_IDLE_RESET_TIMEOUT_MS = 3 * 60 * 60 * 1000;
82102
+ var DEFAULT_RESET_STUCK_THRESHOLD_MS = 120000;
82103
+ var DEFAULT_STOPPING_STUCK_THRESHOLD_MS = 30000;
82104
+ function createInitialManagerState(staleThresholdMs = DEFAULT_STALE_THRESHOLD_MS, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, resetStuckThresholdMs = DEFAULT_RESET_STUCK_THRESHOLD_MS, stoppingStuckThresholdMs = DEFAULT_STOPPING_STUCK_THRESHOLD_MS, idleResetTimeoutMs = DEFAULT_IDLE_RESET_TIMEOUT_MS) {
82105
+ return {
82106
+ agents: {},
82107
+ staleThresholdMs,
82108
+ idleTimeoutMs,
82109
+ idleResetTimeoutMs,
82110
+ resetStuckThresholdMs,
82111
+ stoppingStuckThresholdMs
82008
82112
  };
82009
- const secureGeneration = (filePath) => {
82010
- if (!existsSync12(filePath))
82011
- return true;
82012
- try {
82013
- const stat4 = lstatSync4(filePath);
82014
- if (!stat4.isFile()) {
82015
- if (opts.mode === undefined && !opts.hardMaxBytes)
82113
+ }
82114
+ function reduceManager(state, event) {
82115
+ switch (event.type) {
82116
+ case "session_activity": {
82117
+ const current = state.agents[event.agentId];
82118
+ if (!current || !matchesSession(current, event.sessionInstanceId) || current.status === "stopping")
82119
+ return { state, effects: [] };
82120
+ const agent = clone2(current);
82121
+ const changed = agent.sessionActivity?.status !== event.observation.status;
82122
+ agent.sessionActivity = event.observation;
82123
+ if (sessionBlocksIdleCleanup(agent))
82124
+ agent.idleSince = null;
82125
+ else if (changed && !leaseIsWorking(agent.execution.lease) && agent.pendingAdmissions.length === 0 && agent.inbox.length === 0)
82126
+ agent.idleSince = event.nowMs;
82127
+ return commit(state, agent, []);
82128
+ }
82129
+ case "register":
82130
+ return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId), []);
82131
+ case "wake":
82132
+ return onWake(state, event.agentId, event.message);
82133
+ case "spawned": {
82134
+ const existing = state.agents[event.agentId];
82135
+ if (!existing || existing.status !== "starting")
82136
+ return { state, effects: [] };
82137
+ const agent = clone2(existing);
82138
+ enterStable(agent, "running");
82139
+ syncExecutionProjection(agent);
82140
+ const mode = leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 ? "busy" : "idle";
82141
+ const messages = drainInbox(agent);
82142
+ return commit(state, agent, messages.map((message) => ({ type: "send", agentId: event.agentId, message, mode })));
82143
+ }
82144
+ case "queue_delivery":
82145
+ return mutate(state, event.agentId, (a) => {
82146
+ const queuedById = new Map(a.inbox.filter((message) => message.id).map((message) => [message.id, message]));
82147
+ const restoredIds = new Set;
82148
+ const messages = event.messages.filter((message) => {
82149
+ if (message.id && restoredIds.has(message.id))
82150
+ return false;
82151
+ if (message.id)
82152
+ restoredIds.add(message.id);
82016
82153
  return true;
82017
- report("unsafe_generation", new Error("log generation is not a regular file"));
82018
- return false;
82019
- }
82020
- if (opts.mode !== undefined)
82021
- chmodSync5(filePath, opts.mode);
82022
- if (opts.hardMaxBytes && maxBytes > 0 && stat4.size > maxBytes) {
82023
- try {
82024
- unlinkSync5(filePath);
82025
- } catch (error62) {
82026
- report("oversize_generation", error62);
82027
- return false;
82154
+ }).map((message) => message.id ? queuedById.get(message.id) ?? message : message);
82155
+ a.inbox = [...messages, ...a.inbox.filter((message) => !message.id || !restoredIds.has(message.id))];
82156
+ syncExecutionProjection(a);
82157
+ a.idleSince = null;
82158
+ });
82159
+ case "backend_session":
82160
+ return mutate(state, event.agentId, (a) => {
82161
+ if (event.stalledBefore) {
82162
+ a.stalledSessionId = event.sessionId;
82163
+ } else if (a.stalledSessionId !== null && a.stalledSessionId !== event.sessionId) {
82164
+ a.stalledSessionId = null;
82028
82165
  }
82029
- report("oversize_generation", new Error(`removed generation larger than ${maxBytes} bytes`));
82166
+ a.sessionId = event.sessionId;
82167
+ });
82168
+ case "attach_session": {
82169
+ const existing = state.agents[event.agentId];
82170
+ if (!existing)
82171
+ return { state, effects: [] };
82172
+ const agent = clone2(existing);
82173
+ const effects = recoveryEffects(agent, agent.pendingAdmissions);
82174
+ agent.pendingAdmissions = [];
82175
+ {
82176
+ const a = agent;
82177
+ a.execution = { sessionInstanceId: event.sessionInstanceId, lease: { state: "none", lastTerminal: null } };
82178
+ a.sessionActivity = undefined;
82179
+ a.turnSilence = event.turnSilence ?? {
82180
+ ...DEFAULT_TURN_SILENCE_POLICY,
82181
+ nativeIdleTimeoutMs: state.staleThresholdMs,
82182
+ daemonGraceMs: 0,
82183
+ normalBudgetMs: state.staleThresholdMs
82184
+ };
82185
+ a.lastProgressAt = event.nowMs;
82186
+ a.lastNativeActivityAt = event.nowMs;
82187
+ a.lastNativeActivityKind = null;
82188
+ a.runtimePhase = "admission";
82189
+ a.backendTurnId = null;
82190
+ a.idleSince = null;
82191
+ syncExecutionProjection(a);
82030
82192
  }
82031
- return true;
82032
- } catch (error62) {
82033
- report("chmod", error62);
82034
- return false;
82035
- }
82036
- };
82037
- const rotate = () => {
82038
- try {
82039
- renameSync5(path19, `${path19}.1`);
82040
- if (opts.mode !== undefined)
82041
- chmodSync5(`${path19}.1`, opts.mode);
82042
- return true;
82043
- } catch (error62) {
82044
- report("rotate", error62);
82045
- return false;
82046
- }
82047
- };
82048
- const currentSize = () => {
82049
- try {
82050
- return existsSync12(path19) ? statSync6(path19).size : 0;
82051
- } catch (error62) {
82052
- report("stat", error62);
82053
- return null;
82193
+ return commit(state, agent, effects);
82054
82194
  }
82055
- };
82056
- const sink = {
82057
- secure() {
82058
- return secureGeneration(`${path19}.1`) && secureGeneration(path19);
82059
- },
82060
- write(line) {
82061
- try {
82062
- if (!sink.secure())
82195
+ case "admission_started": {
82196
+ const existing = state.agents[event.agentId];
82197
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82198
+ return { state, effects: [] };
82199
+ return mutate(state, event.agentId, (a) => {
82200
+ if (!matchesSession(a, event.sessionInstanceId))
82063
82201
  return;
82064
- const serialized = line + `
82065
- `;
82066
- const serializedBytes = Buffer.byteLength(serialized, "utf8");
82067
- if (opts.hardMaxBytes && maxBytes > 0 && serializedBytes > maxBytes) {
82068
- report("oversize", new Error(`record exceeds ${maxBytes} bytes`));
82202
+ if (a.pendingAdmissions.some((entry) => entry.commandId === event.commandId))
82069
82203
  return;
82204
+ a.pendingAdmissions = [...a.pendingAdmissions, {
82205
+ sessionInstanceId: event.sessionInstanceId,
82206
+ commandId: event.commandId,
82207
+ exactAgentMsg: event.exactAgentMsg,
82208
+ admittedAt: event.nowMs,
82209
+ driverAcknowledged: false,
82210
+ mode: event.mode,
82211
+ requeueOnFailure: event.requeueOnFailure
82212
+ }];
82213
+ a.idleSince = null;
82214
+ syncExecutionProjection(a);
82215
+ });
82216
+ }
82217
+ case "admission_settled": {
82218
+ const existing = state.agents[event.agentId];
82219
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82220
+ return { state, effects: [] };
82221
+ const record8 = existing.pendingAdmissions.find((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
82222
+ if (!record8)
82223
+ return { state, effects: [] };
82224
+ const agent = clone2(existing);
82225
+ agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId || entry.commandId !== event.commandId);
82226
+ syncExecutionProjection(agent);
82227
+ return commit(state, agent, event.outcome === "failed" ? recoveryEffects(agent, [record8]) : []);
82228
+ }
82229
+ case "admission_acknowledged": {
82230
+ const existing = state.agents[event.agentId];
82231
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82232
+ return { state, effects: [] };
82233
+ if (!existing.pendingAdmissions.some((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId)) {
82234
+ return { state, effects: [] };
82235
+ }
82236
+ return mutate(state, event.agentId, (a) => {
82237
+ a.pendingAdmissions = a.pendingAdmissions.map((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId ? { ...entry, driverAcknowledged: true } : entry);
82238
+ });
82239
+ }
82240
+ case "reset_session":
82241
+ if (!state.agents[event.agentId])
82242
+ return { state, effects: [] };
82243
+ return mutate(state, event.agentId, (a) => {
82244
+ a.sessionId = null;
82245
+ a.stalledSessionId = null;
82246
+ a.idleSince = null;
82247
+ });
82248
+ case "begin_reset":
82249
+ if (!state.agents[event.agentId])
82250
+ return { state, effects: [] };
82251
+ return mutate(state, event.agentId, (a) => {
82252
+ a.resetting = true;
82253
+ a.resettingSince = event.nowMs;
82254
+ const lease = a.execution.lease;
82255
+ if ((lease.state === "active" || lease.state === "suspect_active") && lease.outstandingToolUses !== undefined) {
82256
+ const unblockedLease = { ...lease };
82257
+ delete unblockedLease.outstandingToolUses;
82258
+ delete unblockedLease.outstandingToolCallIds;
82259
+ a.execution.lease = unblockedLease;
82070
82260
  }
82071
- const measuredBytes = currentSize();
82072
- if (measuredBytes === null && opts.hardMaxBytes)
82261
+ });
82262
+ case "rewake_after_reset":
82263
+ if (!state.agents[event.agentId])
82264
+ return { state, effects: [] };
82265
+ return mutate(state, event.agentId, (a) => {
82266
+ a.inbox = [...a.inbox, event.message];
82267
+ a.idleSince = null;
82268
+ });
82269
+ case "runtime_config_queued":
82270
+ return mutate(state, event.agentId, (a) => {
82271
+ if (!a.inbox.some((message) => message.id === event.message.id)) {
82272
+ a.inbox = [...a.inbox, event.message];
82273
+ }
82274
+ syncExecutionProjection(a);
82275
+ a.idleSince = null;
82276
+ });
82277
+ case "runtime_config_applied": {
82278
+ const existing = state.agents[event.agentId];
82279
+ if (!existing)
82280
+ return { state, effects: [] };
82281
+ const agent = clone2(existing);
82282
+ if (agent.status !== "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length === 0)
82283
+ return { state, effects: [] };
82284
+ const messages = drainInbox(agent);
82285
+ return commit(state, agent, messages.map((message) => ({
82286
+ type: "send",
82287
+ agentId: event.agentId,
82288
+ message,
82289
+ mode: "idle"
82290
+ })));
82291
+ }
82292
+ case "turn_started": {
82293
+ const existing = state.agents[event.agentId];
82294
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82295
+ return { state, effects: [] };
82296
+ const current = existing.execution.lease;
82297
+ const nextIdentity = identityOf(event);
82298
+ if ((current.state === "active" || current.state === "suspect_active") && !sameIdentity(current.identity, nextIdentity))
82299
+ return { state, effects: [] };
82300
+ return mutate(state, event.agentId, (a) => {
82301
+ if (!matchesSession(a, event.sessionInstanceId))
82073
82302
  return;
82074
- const currentBytes = measuredBytes ?? 0;
82075
- const shouldRotate = maxBytes > 0 && (opts.hardMaxBytes ? currentBytes > 0 && currentBytes + serializedBytes > maxBytes : currentBytes >= maxBytes);
82076
- if (shouldRotate && !rotate() && opts.hardMaxBytes)
82303
+ const lease = a.execution.lease;
82304
+ const identity3 = identityOf(event);
82305
+ if ((lease.state === "active" || lease.state === "suspect_active") && !sameIdentity(lease.identity, identity3))
82077
82306
  return;
82078
- appendFileSync(path19, serialized, opts.mode === undefined ? undefined : { mode: opts.mode });
82079
- } catch (error62) {
82080
- report("append", error62);
82081
- }
82082
- },
82083
- openSnapshot() {
82084
- const files = [];
82085
- try {
82086
- for (const candidate of [`${path19}.1`, path19]) {
82087
- if (!existsSync12(candidate))
82088
- continue;
82089
- if (!secureGeneration(candidate))
82090
- continue;
82091
- const noFollow = "O_NOFOLLOW" in constants7 ? constants7.O_NOFOLLOW : 0;
82092
- const fd = openSync4(candidate, constants7.O_RDONLY | noFollow);
82093
- try {
82094
- const stat4 = fstatSync2(fd);
82095
- if (!stat4.isFile())
82096
- throw new Error("snapshot source is not a regular file");
82097
- files.push({ path: candidate, fd, size: stat4.size });
82098
- } catch (error62) {
82099
- closeSync4(fd);
82100
- throw error62;
82101
- }
82102
- }
82103
- } catch (error62) {
82104
- for (const file2 of files) {
82105
- try {
82106
- closeSync4(file2.fd);
82107
- } catch {}
82307
+ const startedCommands = new Set(event.commandIds);
82308
+ a.pendingAdmissions = a.pendingAdmissions.filter((entry) => !startedCommands.has(entry.commandId));
82309
+ a.execution.lease = {
82310
+ state: "active",
82311
+ identity: identity3,
82312
+ lastWorkAt: event.nowMs,
82313
+ nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
82314
+ recoveryExtensionsUsed: 0
82315
+ };
82316
+ a.lastProgressAt = event.nowMs;
82317
+ a.lastNativeActivityAt = event.nowMs;
82318
+ a.lastNativeActivityKind = "turn_started";
82319
+ a.runtimePhase = "inference";
82320
+ a.backendTurnId = null;
82321
+ a.idleSince = null;
82322
+ syncExecutionProjection(a);
82323
+ });
82324
+ }
82325
+ case "turn_work": {
82326
+ const existing = state.agents[event.agentId];
82327
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82328
+ return { state, effects: [] };
82329
+ const current = existing.execution.lease;
82330
+ const nextIdentity = identityOf(event);
82331
+ const matchesActive = (current.state === "active" || current.state === "suspect_active") && sameIdentity(current.identity, nextIdentity);
82332
+ const matchesTerminal = current.state === "none" && current.lastTerminal !== null && sameIdentity(current.lastTerminal.identity, nextIdentity);
82333
+ if (!matchesActive && !matchesTerminal)
82334
+ return { state, effects: [] };
82335
+ return mutate(state, event.agentId, (a) => {
82336
+ if (!matchesSession(a, event.sessionInstanceId))
82337
+ return;
82338
+ const lease = a.execution.lease;
82339
+ const identity3 = identityOf(event);
82340
+ if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity3)) {
82341
+ a.execution.lease = {
82342
+ ...lease,
82343
+ lastWorkAt: event.nowMs,
82344
+ nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
82345
+ recoveryExtensionsUsed: 0
82346
+ };
82347
+ } else {
82348
+ const terminal = lease.state === "none" ? lease.lastTerminal : null;
82349
+ if (!terminal || !sameIdentity(terminal.identity, identity3))
82350
+ return;
82351
+ a.execution.lease = {
82352
+ state: "suspect_active",
82353
+ identity: identity3,
82354
+ lastWorkAt: event.nowMs,
82355
+ nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
82356
+ recoveryExtensionsUsed: 0,
82357
+ reason: "work_after_terminal"
82358
+ };
82108
82359
  }
82109
- report("snapshot", error62);
82110
- return { files: [], close: () => {} };
82360
+ a.lastProgressAt = event.nowMs;
82361
+ a.idleSince = null;
82362
+ syncExecutionProjection(a);
82363
+ });
82364
+ }
82365
+ case "turn_tool_started":
82366
+ return onTurnToolLifecycle(state, event, "started");
82367
+ case "turn_tool_finished":
82368
+ return onTurnToolLifecycle(state, event, "finished");
82369
+ case "turn_completed":
82370
+ return onTurnCompleted(state, event.agentId, event.sessionInstanceId, event.nowMs, event.turnId, event.endReason);
82371
+ case "session_closed":
82372
+ if (state.agents[event.agentId]?.execution.sessionInstanceId !== event.sessionInstanceId) {
82373
+ return { state, effects: [] };
82111
82374
  }
82112
- let closed = false;
82113
- return {
82114
- files,
82115
- close() {
82116
- if (closed)
82117
- return;
82118
- closed = true;
82119
- for (const file2 of files) {
82120
- try {
82121
- closeSync4(file2.fd);
82122
- } catch {}
82375
+ {
82376
+ const agent = clone2(state.agents[event.agentId]);
82377
+ const closing = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId === event.sessionInstanceId);
82378
+ agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId);
82379
+ agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
82380
+ agent.sessionActivity = undefined;
82381
+ syncExecutionProjection(agent);
82382
+ return commit(state, agent, recoveryEffects(agent, closing));
82383
+ }
82384
+ case "exit":
82385
+ return onExit(state, event);
82386
+ case "tick":
82387
+ return onTick(state, event.nowMs);
82388
+ case "runtime_signal": {
82389
+ const existing = state.agents[event.agentId];
82390
+ if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82391
+ return { state, effects: [] };
82392
+ const lease = existing.execution.lease;
82393
+ const identity3 = { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
82394
+ if (lease.state !== "active" && lease.state !== "suspect_active" || !sameIdentity(lease.identity, identity3)) {
82395
+ return { state, effects: [] };
82396
+ }
82397
+ return mutate(state, event.agentId, (a) => {
82398
+ const active = a.execution.lease;
82399
+ if (active.state !== "active" && active.state !== "suspect_active" || !sameIdentity(active.identity, identity3))
82400
+ return;
82401
+ if (event.kind === "recovery" && event.recoveryStage !== "recovered") {
82402
+ if (active.recoveryExtensionsUsed < a.turnSilence.maxRecoveryExtensions) {
82403
+ a.execution.lease = {
82404
+ ...active,
82405
+ nativeDeadlineAt: Math.max(active.nativeDeadlineAt, event.nowMs + a.turnSilence.recoveryGraceMs),
82406
+ recoveryExtensionsUsed: active.recoveryExtensionsUsed + 1
82407
+ };
82123
82408
  }
82409
+ } else {
82410
+ a.execution.lease = {
82411
+ ...active,
82412
+ nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs
82413
+ };
82124
82414
  }
82125
- };
82415
+ a.lastNativeActivityAt = event.nowMs;
82416
+ a.lastNativeActivityKind = event.kind;
82417
+ a.runtimePhase = event.phase;
82418
+ if (event.backendTurnId)
82419
+ a.backendTurnId = event.backendTurnId;
82420
+ });
82126
82421
  }
82127
- };
82128
- return sink;
82422
+ case "stall_control_failed":
82423
+ return mutate(state, event.agentId, (a) => {
82424
+ if (event.transition === "clear") {
82425
+ if (a.sessionId === event.sessionId)
82426
+ a.stalledSessionId = event.sessionId;
82427
+ return;
82428
+ }
82429
+ if (a.status !== "stopping")
82430
+ return;
82431
+ const lease = a.execution.lease;
82432
+ if (lease.state !== "active" && lease.state !== "suspect_active")
82433
+ return;
82434
+ a.status = "running";
82435
+ a.stoppingSince = null;
82436
+ a.sessionId = event.sessionId;
82437
+ a.stalledSessionId = event.transition === "fence" ? event.sessionId : null;
82438
+ });
82439
+ case "delivery_rejected":
82440
+ return mutate(state, event.agentId, (a) => {
82441
+ if (!a.inbox.some((message) => message.id === event.message.id)) {
82442
+ a.inbox = [event.message, ...a.inbox];
82443
+ }
82444
+ syncExecutionProjection(a);
82445
+ a.idleSince = null;
82446
+ });
82447
+ }
82129
82448
  }
82130
-
82131
- // src/util/traceSampler.ts
82132
- var SAMPLEABLE_EVENTS = new Set(["tick", "root_work", "runtime_signal"]);
82133
- var SACRED_TURN_SPAN_EVENTS = new Set(["turn_begin", "turn_end", "turn_abort"]);
82134
- var DEFAULT_TRACE_SAMPLE_MS = 30000;
82135
- var DEFAULT_TRACE_FILE_MAX_BYTES = 32 * 1024 * 1024;
82136
- function newAgentState() {
82137
- return {
82138
- lastTickKey: null,
82139
- lastTickEmitAt: Number.NEGATIVE_INFINITY,
82140
- pendingTick: null,
82141
- lastProgressEmitAt: Number.NEGATIVE_INFINITY,
82449
+ function onWake(state, agentId, message) {
82450
+ const existing = state.agents[agentId];
82451
+ const agent = existing ? clone2(existing) : null;
82452
+ if (!agent) {
82453
+ return { state, effects: [] };
82454
+ }
82455
+ agent.recoveryAttempted = message.recovery === true;
82456
+ if (agent.resetting && agent.status !== "idle") {
82457
+ agent.inbox = [...agent.inbox, message];
82458
+ agent.idleSince = null;
82459
+ return commit(state, agent, []);
82460
+ }
82461
+ agent.inbox = [...agent.inbox, message];
82462
+ agent.idleSince = null;
82463
+ if (agent.status === "idle") {
82464
+ agent.status = "starting";
82465
+ const messages = drainInbox(agent);
82466
+ return commit(state, agent, [
82467
+ { type: "spawn", agentId, messages, resumeSessionId: agent.sessionId }
82468
+ ]);
82469
+ }
82470
+ if (agent.status === "running") {
82471
+ if (leaseIsWorking(agent.execution.lease) && agent.inbox.some((queued) => queued.preparedInput?.delivery === "next_turn"))
82472
+ return commit(state, agent, []);
82473
+ const messages = drainInbox(agent);
82474
+ const mode = leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 ? "busy" : "idle";
82475
+ return commit(state, agent, messages.map((queued) => ({ type: "send", agentId, message: queued, mode })));
82476
+ }
82477
+ return commit(state, agent, []);
82478
+ }
82479
+ function onTurnCompleted(state, agentId, sessionInstanceId, nowMs, turnId, endReason) {
82480
+ const existing = state.agents[agentId];
82481
+ if (!existing)
82482
+ return { state, effects: [] };
82483
+ const agent = clone2(existing);
82484
+ if (!matchesSession(agent, sessionInstanceId))
82485
+ return { state, effects: [] };
82486
+ const lease = agent.execution.lease;
82487
+ if (lease.state !== "active" && lease.state !== "suspect_active")
82488
+ return { state, effects: [] };
82489
+ const identity3 = { sessionInstanceId, turnId };
82490
+ if (!sameIdentity(lease.identity, identity3))
82491
+ return { state, effects: [] };
82492
+ const lastTerminal = { identity: identity3, at: nowMs };
82493
+ agent.execution.lease = { state: "none", lastTerminal };
82494
+ agent.lastProgressAt = nowMs;
82495
+ agent.lastNativeActivityAt = nowMs;
82496
+ agent.lastNativeActivityKind = "turn_end";
82497
+ agent.runtimePhase = "terminal";
82498
+ const clearedStallSessionId = endReason === undefined ? agent.stalledSessionId : null;
82499
+ if (clearedStallSessionId !== null)
82500
+ agent.stalledSessionId = null;
82501
+ syncExecutionProjection(agent);
82502
+ const clearEffects = clearedStallSessionId === null ? [] : [{ type: "clear_stall_recovery", agentId, sessionId: clearedStallSessionId }];
82503
+ if (agent.status === "running" && agent.inbox.length > 0 && !agent.resetting) {
82504
+ const messages = drainInbox(agent);
82505
+ return commit(state, agent, [
82506
+ ...clearEffects,
82507
+ ...messages.map((queued) => ({ type: "send", agentId, message: queued, mode: "idle" }))
82508
+ ]);
82509
+ }
82510
+ agent.idleSince = agent.status === "running" && !agent.resetting && !sessionBlocksIdleCleanup(agent) ? nowMs : null;
82511
+ return commit(state, agent, clearEffects);
82512
+ }
82513
+ function onTurnToolLifecycle(state, event, lifecycle) {
82514
+ const existing = state.agents[event.agentId];
82515
+ if (!existing || existing.resetting || existing.execution.sessionInstanceId !== event.sessionInstanceId)
82516
+ return { state, effects: [] };
82517
+ const current = existing.execution.lease;
82518
+ const identity3 = identityOf(event);
82519
+ const matchesActive = (current.state === "active" || current.state === "suspect_active") && sameIdentity(current.identity, identity3);
82520
+ const matchesTerminal = lifecycle === "started" && current.state === "none" && current.lastTerminal !== null && sameIdentity(current.lastTerminal.identity, identity3);
82521
+ if (!matchesActive && !matchesTerminal)
82522
+ return { state, effects: [] };
82523
+ return mutate(state, event.agentId, (agent) => {
82524
+ if (!matchesSession(agent, event.sessionInstanceId))
82525
+ return;
82526
+ const lease = agent.execution.lease;
82527
+ const callId = normalizedToolCallId(event.callId);
82528
+ if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity3)) {
82529
+ const identified = new Set(lease.outstandingToolCallIds ?? []);
82530
+ const currentCount = lease.outstandingToolUses ?? 0;
82531
+ const anonymousCount = Math.max(0, currentCount - identified.size);
82532
+ if (lifecycle === "started") {
82533
+ if (callId && identified.has(callId))
82534
+ return;
82535
+ if (callId)
82536
+ identified.add(callId);
82537
+ } else if (callId) {
82538
+ if (!identified.delete(callId))
82539
+ return;
82540
+ } else if (anonymousCount === 0) {
82541
+ return;
82542
+ }
82543
+ const outstandingToolUses = currentCount + (lifecycle === "started" ? 1 : -1);
82544
+ if (outstandingToolUses > 0) {
82545
+ agent.execution.lease = {
82546
+ ...lease,
82547
+ lastWorkAt: event.nowMs,
82548
+ nativeDeadlineAt: event.nowMs + agent.turnSilence.normalBudgetMs,
82549
+ recoveryExtensionsUsed: 0,
82550
+ outstandingToolUses,
82551
+ ...identified.size > 0 ? { outstandingToolCallIds: [...identified] } : {}
82552
+ };
82553
+ } else {
82554
+ const unblockedLease = { ...lease };
82555
+ delete unblockedLease.outstandingToolUses;
82556
+ delete unblockedLease.outstandingToolCallIds;
82557
+ agent.execution.lease = {
82558
+ ...unblockedLease,
82559
+ lastWorkAt: event.nowMs,
82560
+ nativeDeadlineAt: event.nowMs + agent.turnSilence.normalBudgetMs,
82561
+ recoveryExtensionsUsed: 0
82562
+ };
82563
+ }
82564
+ } else {
82565
+ const terminal = lease.state === "none" ? lease.lastTerminal : null;
82566
+ if (lifecycle !== "started" || !terminal || !sameIdentity(terminal.identity, identity3))
82567
+ return;
82568
+ agent.execution.lease = {
82569
+ state: "suspect_active",
82570
+ identity: identity3,
82571
+ lastWorkAt: event.nowMs,
82572
+ nativeDeadlineAt: event.nowMs + agent.turnSilence.normalBudgetMs,
82573
+ recoveryExtensionsUsed: 0,
82574
+ outstandingToolUses: 1,
82575
+ ...callId ? { outstandingToolCallIds: [callId] } : {},
82576
+ reason: "work_after_terminal"
82577
+ };
82578
+ }
82579
+ agent.lastProgressAt = event.nowMs;
82580
+ agent.lastNativeActivityAt = event.nowMs;
82581
+ agent.lastNativeActivityKind = lifecycle === "started" ? "tool_call" : "tool_output";
82582
+ agent.runtimePhase = lifecycle === "started" ? "tool" : "inference";
82583
+ agent.idleSince = null;
82584
+ syncExecutionProjection(agent);
82585
+ });
82586
+ }
82587
+ function interruptedTurnMessage(agentId, reason, nowMs) {
82588
+ return {
82589
+ id: `${agentId}:recovery:${reason}:${nowMs}`,
82590
+ recovery: true,
82591
+ text: `[System Recovery] Your previous turn was interrupted (${reason}). Run alook message mark list and continue unfinished work or report what is blocked.`
82592
+ };
82593
+ }
82594
+ function onExit(state, event) {
82595
+ const { agentId } = event;
82596
+ const existing = state.agents[agentId];
82597
+ if (!existing)
82598
+ return { state, effects: [] };
82599
+ const agent = clone2(existing);
82600
+ const effects = recoveryEffects(agent, agent.pendingAdmissions);
82601
+ agent.pendingAdmissions = [];
82602
+ agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
82603
+ agent.runtimePhase = "idle";
82604
+ agent.backendTurnId = null;
82605
+ agent.stoppingSince = null;
82606
+ syncExecutionProjection(agent);
82607
+ if (event.interrupted && !agent.recoveryAttempted && agent.inbox.length === 0) {
82608
+ agent.recoveryAttempted = true;
82609
+ agent.inbox.push(interruptedTurnMessage(agentId, event.terminationSemantics ?? "abnormal_exit", event.nowMs ?? 0));
82610
+ }
82611
+ if (agent.inbox.length > 0) {
82612
+ agent.status = "starting";
82613
+ const messages = drainInbox(agent);
82614
+ return commit(state, agent, [
82615
+ ...effects,
82616
+ { type: "spawn", agentId, messages, resumeSessionId: agent.sessionId }
82617
+ ]);
82618
+ }
82619
+ enterStable(agent, "idle");
82620
+ return commit(state, agent, effects);
82621
+ }
82622
+ function onTick(state, nowMs) {
82623
+ const effects = [];
82624
+ const agents = { ...state.agents };
82625
+ for (const id4 of Object.keys(agents)) {
82626
+ const a = agents[id4];
82627
+ const lease = a.execution.lease;
82628
+ const stalled = a.status === "running" && (lease.state === "active" || lease.state === "suspect_active") && (lease.outstandingToolUses ?? 0) === 0 && nowMs - lease.lastWorkAt >= a.turnSilence.normalBudgetMs && nowMs >= lease.nativeDeadlineAt;
82629
+ if (stalled) {
82630
+ const repeatedSessionStall = a.sessionId !== null && a.stalledSessionId === a.sessionId;
82631
+ const forgetSessionId = repeatedSessionStall ? a.sessionId : undefined;
82632
+ agents[id4] = {
82633
+ ...a,
82634
+ status: "stopping",
82635
+ sessionId: repeatedSessionStall ? null : a.sessionId,
82636
+ stalledSessionId: repeatedSessionStall ? null : a.sessionId,
82637
+ idleSince: null,
82638
+ stoppingSince: nowMs
82639
+ };
82640
+ effects.push(forgetSessionId ? { type: "terminate_stalled", agentId: id4, forgetSessionId } : a.sessionId !== null ? { type: "terminate_stalled", agentId: id4, recordSessionId: a.sessionId } : { type: "terminate_stalled", agentId: id4 });
82641
+ continue;
82642
+ }
82643
+ const expiredAdmission = a.status === "running" && a.pendingAdmissions.filter((entry) => !entry.driverAcknowledged && nowMs - entry.admittedAt >= state.staleThresholdMs);
82644
+ if (expiredAdmission && expiredAdmission.length > 0 && a.execution.sessionInstanceId !== null) {
82645
+ agents[id4] = {
82646
+ ...a,
82647
+ pendingAdmissions: a.pendingAdmissions.filter((entry) => !expiredAdmission.includes(entry)),
82648
+ status: "stopping",
82649
+ idleSince: null,
82650
+ stoppingSince: nowMs
82651
+ };
82652
+ effects.push(...recoveryEffects(a, expiredAdmission));
82653
+ effects.push({
82654
+ type: "expire_admission",
82655
+ agentId: id4,
82656
+ sessionInstanceId: a.execution.sessionInstanceId,
82657
+ commandIds: expiredAdmission.map((entry) => entry.commandId)
82658
+ });
82659
+ continue;
82660
+ }
82661
+ const resetStuck = a.resetting && a.status !== "stopping" && a.resettingSince !== null && nowMs - a.resettingSince >= state.resetStuckThresholdMs;
82662
+ if (resetStuck) {
82663
+ agents[id4] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };
82664
+ effects.push({ type: "terminate_stalled", agentId: id4 });
82665
+ continue;
82666
+ }
82667
+ const stoppingStuck = a.status === "stopping" && a.stoppingSince !== null && nowMs - a.stoppingSince >= state.stoppingStuckThresholdMs;
82668
+ if (stoppingStuck) {
82669
+ effects.push({ type: "force_exit", agentId: id4, reason: "stopping_stuck" });
82670
+ continue;
82671
+ }
82672
+ const idleResetEligible = !sessionBlocksIdleCleanup(a) && a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
82673
+ if (idleResetEligible && nowMs - a.idleSince >= state.idleResetTimeoutMs) {
82674
+ agents[id4] = { ...a, idleSince: nowMs };
82675
+ effects.push({ type: "maintain_idle_memory", agentId: id4, sessionId: a.sessionId });
82676
+ continue;
82677
+ }
82678
+ const idleEligible = !sessionBlocksIdleCleanup(a) && a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
82679
+ if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
82680
+ agents[id4] = { ...a, status: "stopping", stoppingSince: nowMs };
82681
+ effects.push({ type: "stop", agentId: id4, reason: "idle_timeout" });
82682
+ }
82683
+ }
82684
+ return { state: { ...state, agents }, effects };
82685
+ }
82686
+ function freshAgent(agentId) {
82687
+ return {
82688
+ agentId,
82689
+ status: "idle",
82690
+ inbox: [],
82691
+ sessionId: null,
82692
+ stalledSessionId: null,
82693
+ execution: { sessionInstanceId: null, lease: { state: "detached" } },
82694
+ pendingAdmissions: [],
82695
+ turnId: null,
82696
+ turnActive: false,
82697
+ lastProgressAt: 0,
82698
+ lastNativeActivityAt: 0,
82699
+ lastNativeActivityKind: null,
82700
+ runtimePhase: "idle",
82701
+ backendTurnId: null,
82702
+ turnSilence: DEFAULT_TURN_SILENCE_POLICY,
82703
+ lastDeliverAt: null,
82704
+ idleSince: null,
82705
+ stoppingSince: null,
82706
+ resetting: false,
82707
+ resettingSince: null
82708
+ };
82709
+ }
82710
+ function enterStable(agent, status) {
82711
+ agent.status = status;
82712
+ if (status === "idle")
82713
+ agent.sessionActivity = undefined;
82714
+ agent.resetting = false;
82715
+ agent.resettingSince = null;
82716
+ agent.stoppingSince = null;
82717
+ }
82718
+ function drainInbox(agent) {
82719
+ const seenIds = new Set;
82720
+ const unique2 = [];
82721
+ for (const m of agent.inbox) {
82722
+ if (m.id && seenIds.has(m.id))
82723
+ continue;
82724
+ if (m.id)
82725
+ seenIds.add(m.id);
82726
+ unique2.push(m);
82727
+ }
82728
+ agent.inbox = [];
82729
+ return unique2;
82730
+ }
82731
+ function clone2(a) {
82732
+ return {
82733
+ ...a,
82734
+ inbox: [...a.inbox],
82735
+ pendingAdmissions: a.pendingAdmissions.map((entry) => ({ ...entry, exactAgentMsg: { ...entry.exactAgentMsg } })),
82736
+ execution: cloneExecution(a.execution)
82737
+ };
82738
+ }
82739
+ function cloneExecution(execution) {
82740
+ if (execution.sessionInstanceId === null)
82741
+ return { sessionInstanceId: null, lease: { state: "detached" } };
82742
+ const lease = execution.lease;
82743
+ return { sessionInstanceId: execution.sessionInstanceId, lease: { ...lease } };
82744
+ }
82745
+ function matchesSession(agent, sessionInstanceId) {
82746
+ return agent.execution.sessionInstanceId === sessionInstanceId;
82747
+ }
82748
+ function identityOf(event) {
82749
+ return { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
82750
+ }
82751
+ function sameIdentity(left, right) {
82752
+ return left.sessionInstanceId === right.sessionInstanceId && left.turnId === right.turnId;
82753
+ }
82754
+ function normalizedToolCallId(rawCallId) {
82755
+ const callId = rawCallId?.trim();
82756
+ return callId && callId.length <= 1024 ? callId : undefined;
82757
+ }
82758
+ function leaseIsWorking(lease) {
82759
+ return lease.state === "active" || lease.state === "suspect_active";
82760
+ }
82761
+ function syncExecutionProjection(agent) {
82762
+ const lease = agent.execution.lease;
82763
+ agent.turnActive = leaseIsWorking(lease) || agent.pendingAdmissions.length > 0;
82764
+ agent.turnId = lease.state === "active" || lease.state === "suspect_active" ? lease.identity.turnId : lease.state === "none" ? lease.lastTerminal?.identity.turnId ?? null : null;
82765
+ agent.lastDeliverAt = agent.pendingAdmissions.length > 0 ? Math.max(...agent.pendingAdmissions.map((entry) => entry.admittedAt)) : null;
82766
+ }
82767
+ function recoveryEffects(agent, records) {
82768
+ return records.filter((record8) => record8.requeueOnFailure).map((record8) => ({
82769
+ type: "requeue_delivery",
82770
+ agentId: agent.agentId,
82771
+ message: record8.exactAgentMsg,
82772
+ mode: record8.mode
82773
+ }));
82774
+ }
82775
+ function commit(state, agent, effects) {
82776
+ return { state: { ...state, agents: { ...state.agents, [agent.agentId]: agent } }, effects };
82777
+ }
82778
+ function mutate(state, agentId, fn) {
82779
+ const existing = state.agents[agentId];
82780
+ if (!existing)
82781
+ return { state, effects: [] };
82782
+ const agent = clone2(existing);
82783
+ fn(agent);
82784
+ return commit(state, agent, []);
82785
+ }
82786
+ function withAgent(state, agentId, make, effects) {
82787
+ const agent = make(state.agents[agentId]);
82788
+ return { state: { ...state, agents: { ...state.agents, [agentId]: agent } }, effects };
82789
+ }
82790
+
82791
+ // src/util/rotatingFileSink.ts
82792
+ import {
82793
+ appendFileSync,
82794
+ chmodSync as chmodSync5,
82795
+ closeSync as closeSync4,
82796
+ constants as constants7,
82797
+ existsSync as existsSync12,
82798
+ fstatSync as fstatSync2,
82799
+ lstatSync as lstatSync4,
82800
+ openSync as openSync4,
82801
+ renameSync as renameSync5,
82802
+ statSync as statSync6,
82803
+ unlinkSync as unlinkSync5
82804
+ } from "node:fs";
82805
+ function createRotatingFileSink(path19, maxBytes, opts = {}) {
82806
+ const report = (operation, error62) => {
82807
+ try {
82808
+ opts.onError?.({ operation, error: error62 });
82809
+ } catch {}
82810
+ };
82811
+ const secureGeneration = (filePath) => {
82812
+ if (!existsSync12(filePath))
82813
+ return true;
82814
+ try {
82815
+ const stat4 = lstatSync4(filePath);
82816
+ if (!stat4.isFile()) {
82817
+ if (opts.mode === undefined && !opts.hardMaxBytes)
82818
+ return true;
82819
+ report("unsafe_generation", new Error("log generation is not a regular file"));
82820
+ return false;
82821
+ }
82822
+ if (opts.mode !== undefined)
82823
+ chmodSync5(filePath, opts.mode);
82824
+ if (opts.hardMaxBytes && maxBytes > 0 && stat4.size > maxBytes) {
82825
+ try {
82826
+ unlinkSync5(filePath);
82827
+ } catch (error62) {
82828
+ report("oversize_generation", error62);
82829
+ return false;
82830
+ }
82831
+ report("oversize_generation", new Error(`removed generation larger than ${maxBytes} bytes`));
82832
+ }
82833
+ return true;
82834
+ } catch (error62) {
82835
+ report("chmod", error62);
82836
+ return false;
82837
+ }
82838
+ };
82839
+ const rotate = () => {
82840
+ try {
82841
+ renameSync5(path19, `${path19}.1`);
82842
+ if (opts.mode !== undefined)
82843
+ chmodSync5(`${path19}.1`, opts.mode);
82844
+ return true;
82845
+ } catch (error62) {
82846
+ report("rotate", error62);
82847
+ return false;
82848
+ }
82849
+ };
82850
+ const currentSize = () => {
82851
+ try {
82852
+ return existsSync12(path19) ? statSync6(path19).size : 0;
82853
+ } catch (error62) {
82854
+ report("stat", error62);
82855
+ return null;
82856
+ }
82857
+ };
82858
+ const sink = {
82859
+ secure() {
82860
+ return secureGeneration(`${path19}.1`) && secureGeneration(path19);
82861
+ },
82862
+ write(line) {
82863
+ try {
82864
+ if (!sink.secure())
82865
+ return;
82866
+ const serialized = line + `
82867
+ `;
82868
+ const serializedBytes = Buffer.byteLength(serialized, "utf8");
82869
+ if (opts.hardMaxBytes && maxBytes > 0 && serializedBytes > maxBytes) {
82870
+ report("oversize", new Error(`record exceeds ${maxBytes} bytes`));
82871
+ return;
82872
+ }
82873
+ const measuredBytes = currentSize();
82874
+ if (measuredBytes === null && opts.hardMaxBytes)
82875
+ return;
82876
+ const currentBytes = measuredBytes ?? 0;
82877
+ const shouldRotate = maxBytes > 0 && (opts.hardMaxBytes ? currentBytes > 0 && currentBytes + serializedBytes > maxBytes : currentBytes >= maxBytes);
82878
+ if (shouldRotate && !rotate() && opts.hardMaxBytes)
82879
+ return;
82880
+ appendFileSync(path19, serialized, opts.mode === undefined ? undefined : { mode: opts.mode });
82881
+ } catch (error62) {
82882
+ report("append", error62);
82883
+ }
82884
+ },
82885
+ openSnapshot() {
82886
+ const files = [];
82887
+ try {
82888
+ for (const candidate of [`${path19}.1`, path19]) {
82889
+ if (!existsSync12(candidate))
82890
+ continue;
82891
+ if (!secureGeneration(candidate))
82892
+ continue;
82893
+ const noFollow = "O_NOFOLLOW" in constants7 ? constants7.O_NOFOLLOW : 0;
82894
+ const fd = openSync4(candidate, constants7.O_RDONLY | noFollow);
82895
+ try {
82896
+ const stat4 = fstatSync2(fd);
82897
+ if (!stat4.isFile())
82898
+ throw new Error("snapshot source is not a regular file");
82899
+ files.push({ path: candidate, fd, size: stat4.size });
82900
+ } catch (error62) {
82901
+ closeSync4(fd);
82902
+ throw error62;
82903
+ }
82904
+ }
82905
+ } catch (error62) {
82906
+ for (const file2 of files) {
82907
+ try {
82908
+ closeSync4(file2.fd);
82909
+ } catch {}
82910
+ }
82911
+ report("snapshot", error62);
82912
+ return { files: [], close: () => {} };
82913
+ }
82914
+ let closed = false;
82915
+ return {
82916
+ files,
82917
+ close() {
82918
+ if (closed)
82919
+ return;
82920
+ closed = true;
82921
+ for (const file2 of files) {
82922
+ try {
82923
+ closeSync4(file2.fd);
82924
+ } catch {}
82925
+ }
82926
+ }
82927
+ };
82928
+ }
82929
+ };
82930
+ return sink;
82931
+ }
82932
+
82933
+ // src/util/traceSampler.ts
82934
+ var SAMPLEABLE_EVENTS = new Set(["tick", "root_work", "runtime_signal"]);
82935
+ var SACRED_TURN_SPAN_EVENTS = new Set(["turn_begin", "turn_end", "turn_abort"]);
82936
+ var DEFAULT_TRACE_SAMPLE_MS = 30000;
82937
+ var DEFAULT_TRACE_FILE_MAX_BYTES = 32 * 1024 * 1024;
82938
+ function newAgentState() {
82939
+ return {
82940
+ lastTickKey: null,
82941
+ lastTickEmitAt: Number.NEGATIVE_INFINITY,
82942
+ pendingTick: null,
82943
+ lastProgressEmitAt: Number.NEGATIVE_INFINITY,
82142
82944
  lastSignalPhase: null,
82143
82945
  lastSignalEmitAt: Number.NEGATIVE_INFINITY
82144
82946
  };
@@ -82977,13 +83779,13 @@ class WsControlChannel {
82977
83779
  }
82978
83780
 
82979
83781
  // src/memory/proxy.ts
82980
- async function handleLocalMemoryCommit(req, res, identity3, commit, onResetError) {
83782
+ async function handleLocalMemoryCommit(req, res, identity3, commit2, onResetError) {
82981
83783
  const json2 = (status, body) => {
82982
83784
  res.writeHead(status, { "content-type": "application/json" });
82983
83785
  res.end(JSON.stringify(body));
82984
83786
  };
82985
83787
  try {
82986
- if (!commit)
83788
+ if (!commit2)
82987
83789
  throw new Error("commit: daemon is not ready");
82988
83790
  const chunks = [];
82989
83791
  let size = 0;
@@ -82997,7 +83799,7 @@ async function handleLocalMemoryCommit(req, res, identity3, commit, onResetError
82997
83799
  const input2 = validateMemoryCommit(JSON.parse(Buffer.concat(chunks).toString("utf8")));
82998
83800
  if (res.destroyed)
82999
83801
  return;
83000
- const result2 = commit(identity3, input2);
83802
+ const result2 = commit2(identity3, input2);
83001
83803
  if (result2.resetSession) {
83002
83804
  req.socket.once("close", () => {
83003
83805
  if (!res.writableFinished)
@@ -83913,698 +84715,6 @@ function joinPath(basePath, reqUrl) {
83913
84715
  const reqPath = reqUrl.startsWith("/") ? reqUrl : `/${reqUrl}`;
83914
84716
  return base + reqPath || "/";
83915
84717
  }
83916
- // src/manager/managerPolicy.ts
83917
- function isActivelyWorking(agent) {
83918
- return agent.status === "running" && (agent.sessionActivity?.status === "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length > 0);
83919
- }
83920
- function sessionBlocksIdleCleanup(agent) {
83921
- return agent.sessionActivity !== undefined && agent.sessionActivity.status !== "idle";
83922
- }
83923
- var DEFAULT_STALE_THRESHOLD_MS = 120000;
83924
- var DEFAULT_TURN_SILENCE_POLICY = {
83925
- nativeIdleTimeoutMs: 300000,
83926
- daemonGraceMs: 60000,
83927
- recoveryGraceMs: 60000,
83928
- maxRecoveryExtensions: 1,
83929
- normalBudgetMs: 360000
83930
- };
83931
- var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
83932
- var DEFAULT_IDLE_RESET_TIMEOUT_MS = 3 * 60 * 60 * 1000;
83933
- var DEFAULT_RESET_STUCK_THRESHOLD_MS = 120000;
83934
- var DEFAULT_STOPPING_STUCK_THRESHOLD_MS = 30000;
83935
- function createInitialManagerState(staleThresholdMs = DEFAULT_STALE_THRESHOLD_MS, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, resetStuckThresholdMs = DEFAULT_RESET_STUCK_THRESHOLD_MS, stoppingStuckThresholdMs = DEFAULT_STOPPING_STUCK_THRESHOLD_MS, idleResetTimeoutMs = DEFAULT_IDLE_RESET_TIMEOUT_MS) {
83936
- return {
83937
- agents: {},
83938
- staleThresholdMs,
83939
- idleTimeoutMs,
83940
- idleResetTimeoutMs,
83941
- resetStuckThresholdMs,
83942
- stoppingStuckThresholdMs
83943
- };
83944
- }
83945
- function reduceManager(state, event) {
83946
- switch (event.type) {
83947
- case "session_activity": {
83948
- const current = state.agents[event.agentId];
83949
- if (!current || !matchesSession(current, event.sessionInstanceId) || current.status === "stopping")
83950
- return { state, effects: [] };
83951
- const agent = clone2(current);
83952
- const changed = agent.sessionActivity?.status !== event.observation.status;
83953
- agent.sessionActivity = event.observation;
83954
- if (sessionBlocksIdleCleanup(agent))
83955
- agent.idleSince = null;
83956
- else if (changed && !leaseIsWorking(agent.execution.lease) && agent.pendingAdmissions.length === 0 && agent.inbox.length === 0)
83957
- agent.idleSince = event.nowMs;
83958
- return commit(state, agent, []);
83959
- }
83960
- case "register":
83961
- return withAgent(state, event.agentId, (a) => a ?? freshAgent(event.agentId), []);
83962
- case "wake":
83963
- return onWake(state, event.agentId, event.message);
83964
- case "spawned": {
83965
- const existing = state.agents[event.agentId];
83966
- if (!existing || existing.status !== "starting")
83967
- return { state, effects: [] };
83968
- const agent = clone2(existing);
83969
- enterStable(agent, "running");
83970
- syncExecutionProjection(agent);
83971
- const mode = leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 ? "busy" : "idle";
83972
- const messages = drainInbox(agent);
83973
- return commit(state, agent, messages.map((message) => ({ type: "send", agentId: event.agentId, message, mode })));
83974
- }
83975
- case "queue_delivery":
83976
- return mutate(state, event.agentId, (a) => {
83977
- const queuedById = new Map(a.inbox.filter((message) => message.id).map((message) => [message.id, message]));
83978
- const restoredIds = new Set;
83979
- const messages = event.messages.filter((message) => {
83980
- if (message.id && restoredIds.has(message.id))
83981
- return false;
83982
- if (message.id)
83983
- restoredIds.add(message.id);
83984
- return true;
83985
- }).map((message) => message.id ? queuedById.get(message.id) ?? message : message);
83986
- a.inbox = [...messages, ...a.inbox.filter((message) => !message.id || !restoredIds.has(message.id))];
83987
- syncExecutionProjection(a);
83988
- a.idleSince = null;
83989
- });
83990
- case "backend_session":
83991
- return mutate(state, event.agentId, (a) => {
83992
- if (event.stalledBefore) {
83993
- a.stalledSessionId = event.sessionId;
83994
- } else if (a.stalledSessionId !== null && a.stalledSessionId !== event.sessionId) {
83995
- a.stalledSessionId = null;
83996
- }
83997
- a.sessionId = event.sessionId;
83998
- });
83999
- case "attach_session": {
84000
- const existing = state.agents[event.agentId];
84001
- if (!existing)
84002
- return { state, effects: [] };
84003
- const agent = clone2(existing);
84004
- const effects = recoveryEffects(agent, agent.pendingAdmissions);
84005
- agent.pendingAdmissions = [];
84006
- {
84007
- const a = agent;
84008
- a.execution = { sessionInstanceId: event.sessionInstanceId, lease: { state: "none", lastTerminal: null } };
84009
- a.sessionActivity = undefined;
84010
- a.turnSilence = event.turnSilence ?? {
84011
- ...DEFAULT_TURN_SILENCE_POLICY,
84012
- nativeIdleTimeoutMs: state.staleThresholdMs,
84013
- daemonGraceMs: 0,
84014
- normalBudgetMs: state.staleThresholdMs
84015
- };
84016
- a.lastProgressAt = event.nowMs;
84017
- a.lastNativeActivityAt = event.nowMs;
84018
- a.lastNativeActivityKind = null;
84019
- a.runtimePhase = "admission";
84020
- a.backendTurnId = null;
84021
- a.idleSince = null;
84022
- syncExecutionProjection(a);
84023
- }
84024
- return commit(state, agent, effects);
84025
- }
84026
- case "admission_started": {
84027
- const existing = state.agents[event.agentId];
84028
- if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84029
- return { state, effects: [] };
84030
- return mutate(state, event.agentId, (a) => {
84031
- if (!matchesSession(a, event.sessionInstanceId))
84032
- return;
84033
- if (a.pendingAdmissions.some((entry) => entry.commandId === event.commandId))
84034
- return;
84035
- a.pendingAdmissions = [...a.pendingAdmissions, {
84036
- sessionInstanceId: event.sessionInstanceId,
84037
- commandId: event.commandId,
84038
- exactAgentMsg: event.exactAgentMsg,
84039
- admittedAt: event.nowMs,
84040
- driverAcknowledged: false,
84041
- mode: event.mode,
84042
- requeueOnFailure: event.requeueOnFailure
84043
- }];
84044
- a.idleSince = null;
84045
- syncExecutionProjection(a);
84046
- });
84047
- }
84048
- case "admission_settled": {
84049
- const existing = state.agents[event.agentId];
84050
- if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84051
- return { state, effects: [] };
84052
- const record8 = existing.pendingAdmissions.find((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
84053
- if (!record8)
84054
- return { state, effects: [] };
84055
- const agent = clone2(existing);
84056
- agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId || entry.commandId !== event.commandId);
84057
- syncExecutionProjection(agent);
84058
- return commit(state, agent, event.outcome === "failed" ? recoveryEffects(agent, [record8]) : []);
84059
- }
84060
- case "admission_acknowledged": {
84061
- const existing = state.agents[event.agentId];
84062
- if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84063
- return { state, effects: [] };
84064
- if (!existing.pendingAdmissions.some((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId)) {
84065
- return { state, effects: [] };
84066
- }
84067
- return mutate(state, event.agentId, (a) => {
84068
- a.pendingAdmissions = a.pendingAdmissions.map((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId ? { ...entry, driverAcknowledged: true } : entry);
84069
- });
84070
- }
84071
- case "reset_session":
84072
- if (!state.agents[event.agentId])
84073
- return { state, effects: [] };
84074
- return mutate(state, event.agentId, (a) => {
84075
- a.sessionId = null;
84076
- a.stalledSessionId = null;
84077
- a.idleSince = null;
84078
- });
84079
- case "begin_reset":
84080
- if (!state.agents[event.agentId])
84081
- return { state, effects: [] };
84082
- return mutate(state, event.agentId, (a) => {
84083
- a.resetting = true;
84084
- a.resettingSince = event.nowMs;
84085
- const lease = a.execution.lease;
84086
- if ((lease.state === "active" || lease.state === "suspect_active") && lease.outstandingToolUses !== undefined) {
84087
- const unblockedLease = { ...lease };
84088
- delete unblockedLease.outstandingToolUses;
84089
- delete unblockedLease.outstandingToolCallIds;
84090
- a.execution.lease = unblockedLease;
84091
- }
84092
- });
84093
- case "rewake_after_reset":
84094
- if (!state.agents[event.agentId])
84095
- return { state, effects: [] };
84096
- return mutate(state, event.agentId, (a) => {
84097
- a.inbox = [...a.inbox, event.message];
84098
- a.idleSince = null;
84099
- });
84100
- case "runtime_config_queued":
84101
- return mutate(state, event.agentId, (a) => {
84102
- if (!a.inbox.some((message) => message.id === event.message.id)) {
84103
- a.inbox = [...a.inbox, event.message];
84104
- }
84105
- syncExecutionProjection(a);
84106
- a.idleSince = null;
84107
- });
84108
- case "runtime_config_applied": {
84109
- const existing = state.agents[event.agentId];
84110
- if (!existing)
84111
- return { state, effects: [] };
84112
- const agent = clone2(existing);
84113
- if (agent.status !== "running" || leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 || agent.inbox.length === 0)
84114
- return { state, effects: [] };
84115
- const messages = drainInbox(agent);
84116
- return commit(state, agent, messages.map((message) => ({
84117
- type: "send",
84118
- agentId: event.agentId,
84119
- message,
84120
- mode: "idle"
84121
- })));
84122
- }
84123
- case "turn_started": {
84124
- const existing = state.agents[event.agentId];
84125
- if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84126
- return { state, effects: [] };
84127
- const current = existing.execution.lease;
84128
- const nextIdentity = identityOf(event);
84129
- if ((current.state === "active" || current.state === "suspect_active") && !sameIdentity(current.identity, nextIdentity))
84130
- return { state, effects: [] };
84131
- return mutate(state, event.agentId, (a) => {
84132
- if (!matchesSession(a, event.sessionInstanceId))
84133
- return;
84134
- const lease = a.execution.lease;
84135
- const identity3 = identityOf(event);
84136
- if ((lease.state === "active" || lease.state === "suspect_active") && !sameIdentity(lease.identity, identity3))
84137
- return;
84138
- const startedCommands = new Set(event.commandIds);
84139
- a.pendingAdmissions = a.pendingAdmissions.filter((entry) => !startedCommands.has(entry.commandId));
84140
- a.execution.lease = {
84141
- state: "active",
84142
- identity: identity3,
84143
- lastWorkAt: event.nowMs,
84144
- nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
84145
- recoveryExtensionsUsed: 0
84146
- };
84147
- a.lastProgressAt = event.nowMs;
84148
- a.lastNativeActivityAt = event.nowMs;
84149
- a.lastNativeActivityKind = "turn_started";
84150
- a.runtimePhase = "inference";
84151
- a.backendTurnId = null;
84152
- a.idleSince = null;
84153
- syncExecutionProjection(a);
84154
- });
84155
- }
84156
- case "turn_work": {
84157
- const existing = state.agents[event.agentId];
84158
- if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84159
- return { state, effects: [] };
84160
- const current = existing.execution.lease;
84161
- const nextIdentity = identityOf(event);
84162
- const matchesActive = (current.state === "active" || current.state === "suspect_active") && sameIdentity(current.identity, nextIdentity);
84163
- const matchesTerminal = current.state === "none" && current.lastTerminal !== null && sameIdentity(current.lastTerminal.identity, nextIdentity);
84164
- if (!matchesActive && !matchesTerminal)
84165
- return { state, effects: [] };
84166
- return mutate(state, event.agentId, (a) => {
84167
- if (!matchesSession(a, event.sessionInstanceId))
84168
- return;
84169
- const lease = a.execution.lease;
84170
- const identity3 = identityOf(event);
84171
- if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity3)) {
84172
- a.execution.lease = {
84173
- ...lease,
84174
- lastWorkAt: event.nowMs,
84175
- nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
84176
- recoveryExtensionsUsed: 0
84177
- };
84178
- } else {
84179
- const terminal = lease.state === "none" ? lease.lastTerminal : null;
84180
- if (!terminal || !sameIdentity(terminal.identity, identity3))
84181
- return;
84182
- a.execution.lease = {
84183
- state: "suspect_active",
84184
- identity: identity3,
84185
- lastWorkAt: event.nowMs,
84186
- nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs,
84187
- recoveryExtensionsUsed: 0,
84188
- reason: "work_after_terminal"
84189
- };
84190
- }
84191
- a.lastProgressAt = event.nowMs;
84192
- a.idleSince = null;
84193
- syncExecutionProjection(a);
84194
- });
84195
- }
84196
- case "turn_tool_started":
84197
- return onTurnToolLifecycle(state, event, "started");
84198
- case "turn_tool_finished":
84199
- return onTurnToolLifecycle(state, event, "finished");
84200
- case "turn_completed":
84201
- return onTurnCompleted(state, event.agentId, event.sessionInstanceId, event.nowMs, event.turnId, event.endReason);
84202
- case "session_closed":
84203
- if (state.agents[event.agentId]?.execution.sessionInstanceId !== event.sessionInstanceId) {
84204
- return { state, effects: [] };
84205
- }
84206
- {
84207
- const agent = clone2(state.agents[event.agentId]);
84208
- const closing = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId === event.sessionInstanceId);
84209
- agent.pendingAdmissions = agent.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId);
84210
- agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
84211
- agent.sessionActivity = undefined;
84212
- syncExecutionProjection(agent);
84213
- return commit(state, agent, recoveryEffects(agent, closing));
84214
- }
84215
- case "exit":
84216
- return onExit(state, event.agentId);
84217
- case "tick":
84218
- return onTick(state, event.nowMs);
84219
- case "runtime_signal": {
84220
- const existing = state.agents[event.agentId];
84221
- if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84222
- return { state, effects: [] };
84223
- const lease = existing.execution.lease;
84224
- const identity3 = { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
84225
- if (lease.state !== "active" && lease.state !== "suspect_active" || !sameIdentity(lease.identity, identity3)) {
84226
- return { state, effects: [] };
84227
- }
84228
- return mutate(state, event.agentId, (a) => {
84229
- const active = a.execution.lease;
84230
- if (active.state !== "active" && active.state !== "suspect_active" || !sameIdentity(active.identity, identity3))
84231
- return;
84232
- if (event.kind === "recovery" && event.recoveryStage !== "recovered") {
84233
- if (active.recoveryExtensionsUsed < a.turnSilence.maxRecoveryExtensions) {
84234
- a.execution.lease = {
84235
- ...active,
84236
- nativeDeadlineAt: Math.max(active.nativeDeadlineAt, event.nowMs + a.turnSilence.recoveryGraceMs),
84237
- recoveryExtensionsUsed: active.recoveryExtensionsUsed + 1
84238
- };
84239
- }
84240
- } else {
84241
- a.execution.lease = {
84242
- ...active,
84243
- nativeDeadlineAt: event.nowMs + a.turnSilence.normalBudgetMs
84244
- };
84245
- }
84246
- a.lastNativeActivityAt = event.nowMs;
84247
- a.lastNativeActivityKind = event.kind;
84248
- a.runtimePhase = event.phase;
84249
- if (event.backendTurnId)
84250
- a.backendTurnId = event.backendTurnId;
84251
- });
84252
- }
84253
- case "stall_control_failed":
84254
- return mutate(state, event.agentId, (a) => {
84255
- if (event.transition === "clear") {
84256
- if (a.sessionId === event.sessionId)
84257
- a.stalledSessionId = event.sessionId;
84258
- return;
84259
- }
84260
- if (a.status !== "stopping")
84261
- return;
84262
- const lease = a.execution.lease;
84263
- if (lease.state !== "active" && lease.state !== "suspect_active")
84264
- return;
84265
- a.status = "running";
84266
- a.stoppingSince = null;
84267
- a.sessionId = event.sessionId;
84268
- a.stalledSessionId = event.transition === "fence" ? event.sessionId : null;
84269
- });
84270
- case "delivery_rejected":
84271
- return mutate(state, event.agentId, (a) => {
84272
- if (!a.inbox.some((message) => message.id === event.message.id)) {
84273
- a.inbox = [event.message, ...a.inbox];
84274
- }
84275
- syncExecutionProjection(a);
84276
- a.idleSince = null;
84277
- });
84278
- }
84279
- }
84280
- function onWake(state, agentId, message) {
84281
- const existing = state.agents[agentId];
84282
- const agent = existing ? clone2(existing) : null;
84283
- if (!agent) {
84284
- return { state, effects: [] };
84285
- }
84286
- if (agent.resetting && agent.status !== "idle") {
84287
- agent.inbox = [...agent.inbox, message];
84288
- agent.idleSince = null;
84289
- return commit(state, agent, []);
84290
- }
84291
- agent.inbox = [...agent.inbox, message];
84292
- agent.idleSince = null;
84293
- if (agent.status === "idle") {
84294
- agent.status = "starting";
84295
- const messages = drainInbox(agent);
84296
- return commit(state, agent, [
84297
- { type: "spawn", agentId, messages, resumeSessionId: agent.sessionId }
84298
- ]);
84299
- }
84300
- if (agent.status === "running") {
84301
- if (leaseIsWorking(agent.execution.lease) && agent.inbox.some((queued) => queued.preparedInput?.delivery === "next_turn"))
84302
- return commit(state, agent, []);
84303
- const messages = drainInbox(agent);
84304
- const mode = leaseIsWorking(agent.execution.lease) || agent.pendingAdmissions.length > 0 ? "busy" : "idle";
84305
- return commit(state, agent, messages.map((queued) => ({ type: "send", agentId, message: queued, mode })));
84306
- }
84307
- return commit(state, agent, []);
84308
- }
84309
- function onTurnCompleted(state, agentId, sessionInstanceId, nowMs, turnId, endReason) {
84310
- const existing = state.agents[agentId];
84311
- if (!existing)
84312
- return { state, effects: [] };
84313
- const agent = clone2(existing);
84314
- if (!matchesSession(agent, sessionInstanceId))
84315
- return { state, effects: [] };
84316
- const lease = agent.execution.lease;
84317
- if (lease.state !== "active" && lease.state !== "suspect_active")
84318
- return { state, effects: [] };
84319
- const identity3 = { sessionInstanceId, turnId };
84320
- if (!sameIdentity(lease.identity, identity3))
84321
- return { state, effects: [] };
84322
- const lastTerminal = { identity: identity3, at: nowMs };
84323
- agent.execution.lease = { state: "none", lastTerminal };
84324
- agent.lastProgressAt = nowMs;
84325
- agent.lastNativeActivityAt = nowMs;
84326
- agent.lastNativeActivityKind = "turn_end";
84327
- agent.runtimePhase = "terminal";
84328
- const clearedStallSessionId = endReason === undefined ? agent.stalledSessionId : null;
84329
- if (clearedStallSessionId !== null)
84330
- agent.stalledSessionId = null;
84331
- syncExecutionProjection(agent);
84332
- const clearEffects = clearedStallSessionId === null ? [] : [{ type: "clear_stall_recovery", agentId, sessionId: clearedStallSessionId }];
84333
- if (agent.status === "running" && agent.inbox.length > 0 && !agent.resetting) {
84334
- const messages = drainInbox(agent);
84335
- return commit(state, agent, [
84336
- ...clearEffects,
84337
- ...messages.map((queued) => ({ type: "send", agentId, message: queued, mode: "idle" }))
84338
- ]);
84339
- }
84340
- agent.idleSince = agent.status === "running" && !agent.resetting && !sessionBlocksIdleCleanup(agent) ? nowMs : null;
84341
- return commit(state, agent, clearEffects);
84342
- }
84343
- function onTurnToolLifecycle(state, event, lifecycle) {
84344
- const existing = state.agents[event.agentId];
84345
- if (!existing || existing.resetting || existing.execution.sessionInstanceId !== event.sessionInstanceId)
84346
- return { state, effects: [] };
84347
- const current = existing.execution.lease;
84348
- const identity3 = identityOf(event);
84349
- const matchesActive = (current.state === "active" || current.state === "suspect_active") && sameIdentity(current.identity, identity3);
84350
- const matchesTerminal = lifecycle === "started" && current.state === "none" && current.lastTerminal !== null && sameIdentity(current.lastTerminal.identity, identity3);
84351
- if (!matchesActive && !matchesTerminal)
84352
- return { state, effects: [] };
84353
- return mutate(state, event.agentId, (agent) => {
84354
- if (!matchesSession(agent, event.sessionInstanceId))
84355
- return;
84356
- const lease = agent.execution.lease;
84357
- const callId = normalizedToolCallId(event.callId);
84358
- if ((lease.state === "active" || lease.state === "suspect_active") && sameIdentity(lease.identity, identity3)) {
84359
- const identified = new Set(lease.outstandingToolCallIds ?? []);
84360
- const currentCount = lease.outstandingToolUses ?? 0;
84361
- const anonymousCount = Math.max(0, currentCount - identified.size);
84362
- if (lifecycle === "started") {
84363
- if (callId && identified.has(callId))
84364
- return;
84365
- if (callId)
84366
- identified.add(callId);
84367
- } else if (callId) {
84368
- if (!identified.delete(callId))
84369
- return;
84370
- } else if (anonymousCount === 0) {
84371
- return;
84372
- }
84373
- const outstandingToolUses = currentCount + (lifecycle === "started" ? 1 : -1);
84374
- if (outstandingToolUses > 0) {
84375
- agent.execution.lease = {
84376
- ...lease,
84377
- lastWorkAt: event.nowMs,
84378
- nativeDeadlineAt: event.nowMs + agent.turnSilence.normalBudgetMs,
84379
- recoveryExtensionsUsed: 0,
84380
- outstandingToolUses,
84381
- ...identified.size > 0 ? { outstandingToolCallIds: [...identified] } : {}
84382
- };
84383
- } else {
84384
- const unblockedLease = { ...lease };
84385
- delete unblockedLease.outstandingToolUses;
84386
- delete unblockedLease.outstandingToolCallIds;
84387
- agent.execution.lease = {
84388
- ...unblockedLease,
84389
- lastWorkAt: event.nowMs,
84390
- nativeDeadlineAt: event.nowMs + agent.turnSilence.normalBudgetMs,
84391
- recoveryExtensionsUsed: 0
84392
- };
84393
- }
84394
- } else {
84395
- const terminal = lease.state === "none" ? lease.lastTerminal : null;
84396
- if (lifecycle !== "started" || !terminal || !sameIdentity(terminal.identity, identity3))
84397
- return;
84398
- agent.execution.lease = {
84399
- state: "suspect_active",
84400
- identity: identity3,
84401
- lastWorkAt: event.nowMs,
84402
- nativeDeadlineAt: event.nowMs + agent.turnSilence.normalBudgetMs,
84403
- recoveryExtensionsUsed: 0,
84404
- outstandingToolUses: 1,
84405
- ...callId ? { outstandingToolCallIds: [callId] } : {},
84406
- reason: "work_after_terminal"
84407
- };
84408
- }
84409
- agent.lastProgressAt = event.nowMs;
84410
- agent.lastNativeActivityAt = event.nowMs;
84411
- agent.lastNativeActivityKind = lifecycle === "started" ? "tool_call" : "tool_output";
84412
- agent.runtimePhase = lifecycle === "started" ? "tool" : "inference";
84413
- agent.idleSince = null;
84414
- syncExecutionProjection(agent);
84415
- });
84416
- }
84417
- function onExit(state, agentId) {
84418
- const existing = state.agents[agentId];
84419
- if (!existing)
84420
- return { state, effects: [] };
84421
- const agent = clone2(existing);
84422
- const effects = recoveryEffects(agent, agent.pendingAdmissions);
84423
- agent.pendingAdmissions = [];
84424
- agent.execution = { sessionInstanceId: null, lease: { state: "detached" } };
84425
- agent.runtimePhase = "idle";
84426
- agent.backendTurnId = null;
84427
- agent.stoppingSince = null;
84428
- syncExecutionProjection(agent);
84429
- if (agent.inbox.length > 0) {
84430
- agent.status = "starting";
84431
- const messages = drainInbox(agent);
84432
- return commit(state, agent, [
84433
- ...effects,
84434
- { type: "spawn", agentId, messages, resumeSessionId: agent.sessionId }
84435
- ]);
84436
- }
84437
- enterStable(agent, "idle");
84438
- return commit(state, agent, effects);
84439
- }
84440
- function onTick(state, nowMs) {
84441
- const effects = [];
84442
- const agents = { ...state.agents };
84443
- for (const id4 of Object.keys(agents)) {
84444
- const a = agents[id4];
84445
- const lease = a.execution.lease;
84446
- const stalled = a.status === "running" && (lease.state === "active" || lease.state === "suspect_active") && (lease.outstandingToolUses ?? 0) === 0 && nowMs - lease.lastWorkAt >= a.turnSilence.normalBudgetMs && nowMs >= lease.nativeDeadlineAt;
84447
- if (stalled) {
84448
- const repeatedSessionStall = a.sessionId !== null && a.stalledSessionId === a.sessionId;
84449
- const forgetSessionId = repeatedSessionStall ? a.sessionId : undefined;
84450
- agents[id4] = {
84451
- ...a,
84452
- status: "stopping",
84453
- sessionId: repeatedSessionStall ? null : a.sessionId,
84454
- stalledSessionId: repeatedSessionStall ? null : a.sessionId,
84455
- idleSince: null,
84456
- stoppingSince: nowMs
84457
- };
84458
- effects.push(forgetSessionId ? { type: "terminate_stalled", agentId: id4, forgetSessionId } : a.sessionId !== null ? { type: "terminate_stalled", agentId: id4, recordSessionId: a.sessionId } : { type: "terminate_stalled", agentId: id4 });
84459
- continue;
84460
- }
84461
- const expiredAdmission = a.status === "running" && a.pendingAdmissions.filter((entry) => !entry.driverAcknowledged && nowMs - entry.admittedAt >= state.staleThresholdMs);
84462
- if (expiredAdmission && expiredAdmission.length > 0 && a.execution.sessionInstanceId !== null) {
84463
- agents[id4] = {
84464
- ...a,
84465
- pendingAdmissions: a.pendingAdmissions.filter((entry) => !expiredAdmission.includes(entry)),
84466
- status: "stopping",
84467
- idleSince: null,
84468
- stoppingSince: nowMs
84469
- };
84470
- effects.push(...recoveryEffects(a, expiredAdmission));
84471
- effects.push({
84472
- type: "expire_admission",
84473
- agentId: id4,
84474
- sessionInstanceId: a.execution.sessionInstanceId,
84475
- commandIds: expiredAdmission.map((entry) => entry.commandId)
84476
- });
84477
- continue;
84478
- }
84479
- const resetStuck = a.resetting && a.status !== "stopping" && a.resettingSince !== null && nowMs - a.resettingSince >= state.resetStuckThresholdMs;
84480
- if (resetStuck) {
84481
- agents[id4] = { ...a, status: "stopping", idleSince: null, stoppingSince: nowMs };
84482
- effects.push({ type: "terminate_stalled", agentId: id4 });
84483
- continue;
84484
- }
84485
- const stoppingStuck = a.status === "stopping" && a.stoppingSince !== null && nowMs - a.stoppingSince >= state.stoppingStuckThresholdMs;
84486
- if (stoppingStuck) {
84487
- effects.push({ type: "force_exit", agentId: id4, reason: "stopping_stuck" });
84488
- continue;
84489
- }
84490
- const idleResetEligible = !sessionBlocksIdleCleanup(a) && a.idleSince !== null && a.sessionId !== null && a.inbox.length === 0 && a.pendingAdmissions.length === 0 && !a.resetting && state.idleResetTimeoutMs > 0 && Number.isFinite(state.idleResetTimeoutMs) && (a.status === "idle" && lease.state === "detached" || a.status === "running" && lease.state === "none" && lease.lastTerminal !== null);
84491
- if (idleResetEligible && nowMs - a.idleSince >= state.idleResetTimeoutMs) {
84492
- agents[id4] = { ...a, idleSince: nowMs };
84493
- effects.push({ type: "maintain_idle_memory", agentId: id4, sessionId: a.sessionId });
84494
- continue;
84495
- }
84496
- const idleEligible = !sessionBlocksIdleCleanup(a) && a.status === "running" && lease.state === "none" && a.pendingAdmissions.length === 0 && lease.lastTerminal !== null && a.inbox.length === 0 && state.idleTimeoutMs > 0 && Number.isFinite(state.idleTimeoutMs);
84497
- if (idleEligible && a.idleSince !== null && nowMs - a.idleSince >= state.idleTimeoutMs) {
84498
- agents[id4] = { ...a, status: "stopping", stoppingSince: nowMs };
84499
- effects.push({ type: "stop", agentId: id4, reason: "idle_timeout" });
84500
- }
84501
- }
84502
- return { state: { ...state, agents }, effects };
84503
- }
84504
- function freshAgent(agentId) {
84505
- return {
84506
- agentId,
84507
- status: "idle",
84508
- inbox: [],
84509
- sessionId: null,
84510
- stalledSessionId: null,
84511
- execution: { sessionInstanceId: null, lease: { state: "detached" } },
84512
- pendingAdmissions: [],
84513
- turnId: null,
84514
- turnActive: false,
84515
- lastProgressAt: 0,
84516
- lastNativeActivityAt: 0,
84517
- lastNativeActivityKind: null,
84518
- runtimePhase: "idle",
84519
- backendTurnId: null,
84520
- turnSilence: DEFAULT_TURN_SILENCE_POLICY,
84521
- lastDeliverAt: null,
84522
- idleSince: null,
84523
- stoppingSince: null,
84524
- resetting: false,
84525
- resettingSince: null
84526
- };
84527
- }
84528
- function enterStable(agent, status) {
84529
- agent.status = status;
84530
- if (status === "idle")
84531
- agent.sessionActivity = undefined;
84532
- agent.resetting = false;
84533
- agent.resettingSince = null;
84534
- agent.stoppingSince = null;
84535
- }
84536
- function drainInbox(agent) {
84537
- const seenIds = new Set;
84538
- const unique2 = [];
84539
- for (const m of agent.inbox) {
84540
- if (m.id && seenIds.has(m.id))
84541
- continue;
84542
- if (m.id)
84543
- seenIds.add(m.id);
84544
- unique2.push(m);
84545
- }
84546
- agent.inbox = [];
84547
- return unique2;
84548
- }
84549
- function clone2(a) {
84550
- return {
84551
- ...a,
84552
- inbox: [...a.inbox],
84553
- pendingAdmissions: a.pendingAdmissions.map((entry) => ({ ...entry, exactAgentMsg: { ...entry.exactAgentMsg } })),
84554
- execution: cloneExecution(a.execution)
84555
- };
84556
- }
84557
- function cloneExecution(execution) {
84558
- if (execution.sessionInstanceId === null)
84559
- return { sessionInstanceId: null, lease: { state: "detached" } };
84560
- const lease = execution.lease;
84561
- return { sessionInstanceId: execution.sessionInstanceId, lease: { ...lease } };
84562
- }
84563
- function matchesSession(agent, sessionInstanceId) {
84564
- return agent.execution.sessionInstanceId === sessionInstanceId;
84565
- }
84566
- function identityOf(event) {
84567
- return { sessionInstanceId: event.sessionInstanceId, turnId: event.turnId };
84568
- }
84569
- function sameIdentity(left, right) {
84570
- return left.sessionInstanceId === right.sessionInstanceId && left.turnId === right.turnId;
84571
- }
84572
- function normalizedToolCallId(rawCallId) {
84573
- const callId = rawCallId?.trim();
84574
- return callId && callId.length <= 1024 ? callId : undefined;
84575
- }
84576
- function leaseIsWorking(lease) {
84577
- return lease.state === "active" || lease.state === "suspect_active";
84578
- }
84579
- function syncExecutionProjection(agent) {
84580
- const lease = agent.execution.lease;
84581
- agent.turnActive = leaseIsWorking(lease) || agent.pendingAdmissions.length > 0;
84582
- agent.turnId = lease.state === "active" || lease.state === "suspect_active" ? lease.identity.turnId : lease.state === "none" ? lease.lastTerminal?.identity.turnId ?? null : null;
84583
- agent.lastDeliverAt = agent.pendingAdmissions.length > 0 ? Math.max(...agent.pendingAdmissions.map((entry) => entry.admittedAt)) : null;
84584
- }
84585
- function recoveryEffects(agent, records) {
84586
- return records.filter((record8) => record8.requeueOnFailure).map((record8) => ({
84587
- type: "requeue_delivery",
84588
- agentId: agent.agentId,
84589
- message: record8.exactAgentMsg,
84590
- mode: record8.mode
84591
- }));
84592
- }
84593
- function commit(state, agent, effects) {
84594
- return { state: { ...state, agents: { ...state.agents, [agent.agentId]: agent } }, effects };
84595
- }
84596
- function mutate(state, agentId, fn) {
84597
- const existing = state.agents[agentId];
84598
- if (!existing)
84599
- return { state, effects: [] };
84600
- const agent = clone2(existing);
84601
- fn(agent);
84602
- return commit(state, agent, []);
84603
- }
84604
- function withAgent(state, agentId, make, effects) {
84605
- const agent = make(state.agents[agentId]);
84606
- return { state: { ...state, agents: { ...state.agents, [agentId]: agent } }, effects };
84607
- }
84608
84718
  // src/manager/memoryReviewPrompt.ts
84609
84719
  var MEMORY_REVIEW_STEPS = `1. Consistency: Read recent .commits.jsonl entries, memory.md and experiences. Use the last review node and unfinished review coverage to guide this review. Merge duplicates and resolve conflicting notes against original decisions. Check links.
84610
84720
  2. Facts: Verify claims, especially work progress, against the latest original records. Search the context timeline and task discussions through their latest outcomes. Correct outdated or unsupported claims; keep uncertainty explicit.
@@ -84689,13 +84799,13 @@ function messagingSection() {
84689
84799
  "",
84690
84800
  "`--remind-after T` is required on every send and controls whether a local follow-up is " + "armed for the same channel, thread, or DM.",
84691
84801
  "",
84692
- "- Use `1m` to `24h` when silence would leave work unfinished — for example, after a question, " + "approval request, handoff, or blocker. If no newer message arrives by T, you will be reminded " + "to return; a newer message or daemon restart cancels the timer.",
84802
+ "- Use `1m` to `24h` when silence would leave work unfinished — for example, after a question, " + "approval request, handoff, or blocker. If no newer message arrives by T, you will be reminded " + "to return; a newer message cancels the timer. Daemon restarts preserve it.",
84693
84803
  "- Use `0` only when no later action depends on a reply. It disables the timer.",
84694
84804
  "",
84695
84805
  "#### Schedule future or recurring work",
84696
84806
  "",
84697
- "- Use `--remind-after` (`1m` to `24h`) only to follow up when an active conversation goes quiet; a newer message or daemon restart cancels it.",
84698
- `- Use \`${CLI} schedule\` for tasks that must run at a specific future time (>24h or across restarts/offline machines) or on a recurring cadence (\`hourly\`/\`daily\`/\`weekly\`/\`monthly\`), visible in Home -> Schedule. Always bind the request's message ref, and run \`--ack\` after finishing a triggered run.`,
84807
+ "- Use `--remind-after` (`1m` to `24h`) only to follow up when an active conversation goes quiet; a newer message cancels it.",
84808
+ `- Use \`${CLI} schedule\` for tasks that must run at a specific future time (>24h or across restarts/offline machines) or on a recurring cadence (\`hourly\`/\`daily\`/\`weekly\`/\`monthly\`), visible in Home -> Schedule. Always bind the request's message ref, and run \`--ack "<short result>"\` (<= 1 KiB UTF-8) after finishing a triggered run.`,
84699
84809
  "",
84700
84810
  "#### Sending mechanics",
84701
84811
  "",
@@ -84882,9 +84992,9 @@ function cliCommandsSection() {
84882
84992
  "",
84883
84993
  "Your household shares one bot schedule visible to your owner in Home -> Schedule and to sibling bots. Every scheduled task binds to a concrete message ref.",
84884
84994
  "",
84885
- `1. \`${CLI} schedule list [--from <iso> --to <iso>] [--creator <handle>]\` — list scheduled tasks and, when \`--from\` and \`--to\` are given, expanded occurrences.`,
84995
+ `1. \`${CLI} schedule list [--from <iso> --to <iso>] [--creator <handle>]\` — list scheduled tasks and, when \`--from\` and \`--to\` are given (up to 62 days), expanded occurrences including past completed runs and their \`ackResult\` summaries.`,
84886
84996
  `2. \`${CLI} schedule create --title <text> --at <iso> --message <ref> [--description <text>] [--tz <iana>] [--duration <minutes>] [--repeat <hourly|daily|weekly|monthly>] [--interval <n>] [--weekdays <days>] [--until <iso>] [--count <n>]\` — create a one-time or recurring task bound to a message you can read.`,
84887
- `3. \`${CLI} schedule update <id> [fields...] [--message <ref>] [--ack]\` — update a task, or pass \`--ack\` after finishing the triggered run to mark it completed.`,
84997
+ `3. \`${CLI} schedule update <id> [fields...] [--message <ref>] [--ack "<short result>"]\` — update a task, or pass \`--ack "<short result>"\` (non-empty summary, max 1 KiB UTF-8) after finishing the triggered run to mark it completed and record its outcome.`,
84888
84998
  `4. \`${CLI} schedule delete <id>\` — delete a scheduled task.`,
84889
84999
  "",
84890
85000
  "### Pages",
@@ -85635,6 +85745,9 @@ class AgentProcessManager {
85635
85745
  const session2 = this.sessions.get(agentId);
85636
85746
  if (!session2)
85637
85747
  return;
85748
+ const owner = this.activeSpawnState.get(agentId);
85749
+ if (owner)
85750
+ owner.terminationSemantics = "owner_request";
85638
85751
  this.abortCurrentTurn(agentId, "requested_stop");
85639
85752
  await session2.stop({ reason: "owner_request", forceAfterMs: SESSION_STOP_GRACE_MS2 });
85640
85753
  if (this.sessions.get(agentId) === session2)
@@ -85701,6 +85814,12 @@ class AgentProcessManager {
85701
85814
  snapshot() {
85702
85815
  return this.state;
85703
85816
  }
85817
+ interruptedTurns() {
85818
+ return Object.values(this.state.agents).filter((agent) => {
85819
+ const owner = this.activeSpawnState.get(agent.agentId);
85820
+ return agent.turnActive && !agent.recoveryAttempted && !agent.resetting && !owner?.discardEvents && !["owner_request", "idle_stop", "force_exit"].includes(owner?.terminationSemantics ?? "");
85821
+ }).map(({ agentId, sessionId }) => ({ agentId, sessionId }));
85822
+ }
85704
85823
  runningAgentCount() {
85705
85824
  return this.sessions.size;
85706
85825
  }
@@ -86189,6 +86308,8 @@ ${this.opts.wakePromptFooter}` : text7;
86189
86308
  });
86190
86309
  }
86191
86310
  if (effect.type === "terminate_stalled" && spawnState) {
86311
+ if (this.state.agents[effect.agentId]?.turnActive)
86312
+ spawnState.hadActiveTurnAtInterrupt = true;
86192
86313
  this.closeTurn(spawnState, spawnState.activeSpan, {
86193
86314
  event: "turn_abort",
86194
86315
  abortCause: "terminate_stalled"
@@ -86363,6 +86484,7 @@ ${this.opts.wakePromptFooter}` : text7;
86363
86484
  stalledSessionIdAtLaunch,
86364
86485
  spawnFailureReason: null,
86365
86486
  terminationSemantics: null,
86487
+ hadActiveTurnAtInterrupt: false,
86366
86488
  spawnOrdinal: this.nextSpawnOrdinal++,
86367
86489
  launchIdSnapshot: typeof ctx.launchId === "string" && ctx.launchId.length > 0 ? ctx.launchId : null,
86368
86490
  nextTurnOrdinal: 1,
@@ -86420,6 +86542,7 @@ ${this.opts.wakePromptFooter}` : text7;
86420
86542
  const exitSignal = "signal" in result2 ? result2.signal ?? null : null;
86421
86543
  const requested = "requested" in result2 && result2.requested === true;
86422
86544
  const abnormal = !requested && (exitSignal !== null || exitCode !== null && exitCode !== 0);
86545
+ const interrupted = !this.shuttingDown && state.hasEstablished && !state.superseded && !state.discardEvents && (state.hadActiveTurnAtInterrupt || this.state.agents[agentId]?.turnActive === true) && (state.terminationSemantics === "killed_stalled" || result2.outcome === "crashed" && state.terminationSemantics === null);
86423
86546
  if (state.hasEstablished && !state.suppressExitLog) {
86424
86547
  this.logSessionEnded(agentId, "exit");
86425
86548
  if (abnormal) {
@@ -86448,7 +86571,9 @@ ${this.opts.wakePromptFooter}` : text7;
86448
86571
  exitSignal,
86449
86572
  abnormal,
86450
86573
  spawnFailureReason: state.spawnFailureReason,
86451
- terminationSemantics: state.terminationSemantics
86574
+ terminationSemantics: state.terminationSemantics,
86575
+ interrupted,
86576
+ nowMs: this.now()
86452
86577
  }, state);
86453
86578
  };
86454
86579
  const onEvent = (event) => {
@@ -86462,8 +86587,12 @@ ${this.opts.wakePromptFooter}` : text7;
86462
86587
  this.onAgentEvent(agentId, event, driver.id, state);
86463
86588
  return;
86464
86589
  }
86465
- if (event.type === "session_failed" && !state.hasEstablished) {
86466
- reportSpawnFailure(event.error.code || "failed_to_start", { message: event.error.message });
86590
+ if (event.type === "session_failed") {
86591
+ if (this.state.agents[agentId]?.turnActive)
86592
+ state.hadActiveTurnAtInterrupt = true;
86593
+ if (!state.hasEstablished) {
86594
+ reportSpawnFailure(event.error.code || "failed_to_start", { message: event.error.message });
86595
+ }
86467
86596
  }
86468
86597
  if (event.type === "session_started") {
86469
86598
  const persisted = this.opts.timeline?.setSession(agentId, event.backendSessionId, event.sessionInstanceId);
@@ -87069,6 +87198,12 @@ class AgentRouter {
87069
87198
  this.log.info("agent removed from running set (local stop)", { agentId });
87070
87199
  this.scheduleReadyFrameResend();
87071
87200
  }
87201
+ markLocallyStarted(agentId) {
87202
+ if (this.running.has(agentId))
87203
+ return;
87204
+ this.running.add(agentId);
87205
+ this.scheduleReadyFrameResend();
87206
+ }
87072
87207
  scheduleReadyFrameResend() {
87073
87208
  if (this.pendingResend)
87074
87209
  return;
@@ -88723,6 +88858,15 @@ function createMachineStopCommandListener(onStopRequested) {
88723
88858
  }
88724
88859
 
88725
88860
  // src/daemon/messageReminderScheduler.ts
88861
+ import { readFileSync as readFileSync11 } from "node:fs";
88862
+ var savedReminder = exports_external.object({
88863
+ agentId: exports_external.string().min(1),
88864
+ channel: exports_external.string().min(1),
88865
+ sentSeq: exports_external.number().int().nonnegative(),
88866
+ remindAfterMs: exports_external.number().int().min(1).max(86400000),
88867
+ startedAt: exports_external.number().nonnegative(),
88868
+ dueAt: exports_external.number().nonnegative()
88869
+ }).refine((value) => value.dueAt === value.startedAt + value.remindAfterMs);
88726
88870
  function reminderKey(agentId, channel) {
88727
88871
  return `${agentId}\x00${channel}`;
88728
88872
  }
@@ -88742,6 +88886,25 @@ class MessageReminderScheduler {
88742
88886
  this.now = options.now ?? Date.now;
88743
88887
  this.setTimer = options.setTimer ?? ((callback, delayMs) => setTimeout(callback, delayMs));
88744
88888
  this.clearTimer = options.clearTimer ?? ((timer) => clearTimeout(timer));
88889
+ if (options.filePath) {
88890
+ let saved;
88891
+ try {
88892
+ saved = JSON.parse(readFileSync11(options.filePath, "utf8"));
88893
+ } catch {
88894
+ return;
88895
+ }
88896
+ if (Array.isArray(saved))
88897
+ for (const value of saved) {
88898
+ const parsed = savedReminder.safeParse(value);
88899
+ if (!parsed.success)
88900
+ continue;
88901
+ const record8 = parsed.data;
88902
+ this.reminders.set(reminderKey(record8.agentId, record8.channel), {
88903
+ ...record8,
88904
+ sentRef: `${record8.channel}#${record8.sentSeq}`
88905
+ });
88906
+ }
88907
+ }
88745
88908
  }
88746
88909
  arm(input2) {
88747
88910
  const key = reminderKey(input2.agentId, input2.channel);
@@ -88753,7 +88916,7 @@ class MessageReminderScheduler {
88753
88916
  if (latest !== undefined && latest > input2.sentSeq) {
88754
88917
  return { armed: false, reason: "newer_message_observed" };
88755
88918
  }
88756
- this.clearReminder(key);
88919
+ const previous4 = this.reminders.get(key);
88757
88920
  const startedAt = this.now();
88758
88921
  const dueAt = startedAt + input2.remindAfterMs;
88759
88922
  const sentRef = `${input2.channel}#${input2.sentSeq}`;
@@ -88761,24 +88924,44 @@ class MessageReminderScheduler {
88761
88924
  ...input2,
88762
88925
  sentRef,
88763
88926
  startedAt,
88764
- dueAt,
88765
- timer: undefined
88927
+ dueAt
88766
88928
  };
88929
+ this.reminders.set(key, record8);
88930
+ try {
88931
+ this.persist();
88932
+ } catch (error62) {
88933
+ if (previous4)
88934
+ this.reminders.set(key, previous4);
88935
+ else
88936
+ this.reminders.delete(key);
88937
+ throw error62;
88938
+ }
88939
+ if (previous4?.timer !== undefined)
88940
+ this.clearTimer(previous4.timer);
88941
+ this.schedule(key, record8);
88942
+ return { armed: true, dueAt };
88943
+ }
88944
+ restore() {
88945
+ for (const [key, record8] of this.reminders) {
88946
+ if (record8.timer === undefined)
88947
+ this.schedule(key, record8);
88948
+ }
88949
+ }
88950
+ schedule(key, record8) {
88767
88951
  record8.timer = this.setTimer(() => {
88768
88952
  if (this.reminders.get(key) !== record8)
88769
88953
  return;
88770
88954
  this.reminders.delete(key);
88771
88955
  try {
88772
- const delivery = this.options.deliver(input2.agentId, {
88773
- id: `${input2.agentId}:reminder:${input2.channel}:${input2.sentSeq}:${startedAt}`,
88774
- text: reminderPrompt(input2.channel, sentRef, startedAt)
88956
+ this.persist();
88957
+ const delivery = this.options.deliver(record8.agentId, {
88958
+ id: `${record8.agentId}:reminder:${record8.channel}:${record8.sentSeq}:${record8.startedAt}`,
88959
+ text: reminderPrompt(record8.channel, record8.sentRef, record8.startedAt)
88775
88960
  });
88776
88961
  Promise.resolve(delivery).catch(() => {});
88777
88962
  } catch {}
88778
- }, input2.remindAfterMs);
88963
+ }, Math.max(0, record8.dueAt - this.now()));
88779
88964
  record8.timer.unref?.();
88780
- this.reminders.set(key, record8);
88781
- return { armed: true, dueAt };
88782
88965
  }
88783
88966
  observe(agentId, channel, latestSeq) {
88784
88967
  const key = reminderKey(agentId, channel);
@@ -88792,26 +88975,44 @@ class MessageReminderScheduler {
88792
88975
  }
88793
88976
  clearAgent(agentId) {
88794
88977
  const prefix = `${agentId}\x00`;
88978
+ let changed = false;
88795
88979
  for (const key of [...this.reminders.keys()]) {
88796
- if (key.startsWith(prefix))
88797
- this.clearReminder(key);
88980
+ if (key.startsWith(prefix)) {
88981
+ this.clearReminder(key, false);
88982
+ changed = true;
88983
+ }
88798
88984
  }
88799
88985
  for (const key of [...this.latestObservedSeq.keys()]) {
88800
88986
  if (key.startsWith(prefix))
88801
88987
  this.latestObservedSeq.delete(key);
88802
88988
  }
88989
+ if (changed)
88990
+ this.persist();
88803
88991
  }
88804
88992
  clearAll() {
88805
- for (const key of [...this.reminders.keys()])
88806
- this.clearReminder(key);
88993
+ this.stop();
88994
+ this.persist();
88995
+ }
88996
+ stop() {
88997
+ for (const record8 of this.reminders.values())
88998
+ if (record8.timer !== undefined)
88999
+ this.clearTimer(record8.timer);
89000
+ this.reminders.clear();
88807
89001
  this.latestObservedSeq.clear();
88808
89002
  }
88809
- clearReminder(key) {
89003
+ persist() {
89004
+ if (this.options.filePath)
89005
+ writePrivateJsonAtomic(this.options.filePath, [...this.reminders.values()].map(({ agentId, channel, sentSeq, remindAfterMs, startedAt, dueAt }) => ({ agentId, channel, sentSeq, remindAfterMs, startedAt, dueAt })));
89006
+ }
89007
+ clearReminder(key, persist = true) {
88810
89008
  const reminder = this.reminders.get(key);
88811
89009
  if (!reminder)
88812
89010
  return;
88813
89011
  this.reminders.delete(key);
88814
- this.clearTimer(reminder.timer);
89012
+ if (reminder.timer !== undefined)
89013
+ this.clearTimer(reminder.timer);
89014
+ if (persist)
89015
+ this.persist();
88815
89016
  }
88816
89017
  }
88817
89018
 
@@ -88979,7 +89180,7 @@ function createDaemonAgentDriverHost(ctx, onRawLine, onRawStderr) {
88979
89180
  }
88980
89181
 
88981
89182
  // src/drivers/alookPageGuide.ts
88982
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, writeFileSync as writeFileSync13 } from "node:fs";
89183
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync12, writeFileSync as writeFileSync13 } from "node:fs";
88983
89184
  import { join as join29 } from "node:path";
88984
89185
  var ALOOK_PAGE_GUIDE_FILENAME = "alook-page.md";
88985
89186
  var ALOOK_PAGE_GUIDE_CONTENT = [
@@ -89043,7 +89244,7 @@ function syncAlookPageGuide(workingDirectory) {
89043
89244
  mkdirSync11(workingDirectory, { recursive: true });
89044
89245
  const target2 = join29(workingDirectory, ALOOK_PAGE_GUIDE_FILENAME);
89045
89246
  try {
89046
- if (readFileSync11(target2, "utf8") === ALOOK_PAGE_GUIDE_CONTENT)
89247
+ if (readFileSync12(target2, "utf8") === ALOOK_PAGE_GUIDE_CONTENT)
89047
89248
  return false;
89048
89249
  } catch (error62) {
89049
89250
  if (error62?.code !== "ENOENT")
@@ -89473,6 +89674,8 @@ var WARMUP_CEILING_MS = 30000;
89473
89674
  var RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;
89474
89675
  var RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";
89475
89676
  var STATUS_WRITE_INTERVAL_MS = 5000;
89677
+ var interruptedTurn = exports_external.object({ agentId: exports_external.string().min(1), sessionId: exports_external.string().nullable(), interruptedAt: exports_external.number().nonnegative() });
89678
+ var RECOVERY_TTL_MS = 15 * 60000;
89476
89679
  function parseRuntimeRawTraceAgentIds(value) {
89477
89680
  return new Set((value ?? "").split(",").map((agentId) => agentId.trim()).filter((agentId) => agentId.length > 0 && agentId !== "*"));
89478
89681
  }
@@ -89714,6 +89917,37 @@ async function createDaemon(opts) {
89714
89917
  }
89715
89918
  };
89716
89919
  let reminderSchedulerRef = null;
89920
+ const recoveryPath = opts.daemonDir ? join31(opts.daemonDir, "interrupted-turns.json") : undefined;
89921
+ let interruptedTurns = [];
89922
+ const localMessageEpochs = new Map;
89923
+ if (recoveryPath) {
89924
+ try {
89925
+ const parsed = JSON.parse(readFileSync13(recoveryPath, "utf8"));
89926
+ if (Array.isArray(parsed))
89927
+ interruptedTurns = parsed.flatMap((value) => {
89928
+ const record8 = interruptedTurn.safeParse(value);
89929
+ return record8.success ? [record8.data] : [];
89930
+ });
89931
+ } catch {
89932
+ interruptedTurns = [];
89933
+ }
89934
+ }
89935
+ const persistInterruptedTurns = () => {
89936
+ if (recoveryPath)
89937
+ writePrivateJsonAtomic(recoveryPath, interruptedTurns);
89938
+ };
89939
+ const clearInterruptedTurn = (agentId) => {
89940
+ if (!interruptedTurns.some((record8) => record8.agentId === agentId))
89941
+ return;
89942
+ const previous4 = interruptedTurns;
89943
+ interruptedTurns = interruptedTurns.filter((record8) => record8.agentId !== agentId);
89944
+ try {
89945
+ persistInterruptedTurns();
89946
+ } catch (error62) {
89947
+ interruptedTurns = previous4;
89948
+ throw error62;
89949
+ }
89950
+ };
89717
89951
  const selfSleepScheduler = opts.onSelfSleep ? new DaemonSelfSleepScheduler({
89718
89952
  onSleep: opts.onSelfSleep,
89719
89953
  ...opts.selfSleepClock ? { clock: opts.selfSleepClock } : {}
@@ -89832,7 +90066,8 @@ async function createDaemon(opts) {
89832
90066
  async function listMyBotsHttp(includeInactive = false) {
89833
90067
  const res = await fetch(`${opts.serverUrl}/api/community/daemon/bots${includeInactive ? "?includeInactive=true" : ""}`, {
89834
90068
  method: "GET",
89835
- headers: { authorization: `Bearer ${opts.machineKey}` }
90069
+ headers: { authorization: `Bearer ${opts.machineKey}` },
90070
+ signal: AbortSignal.any([stopAbort.signal, AbortSignal.timeout(1e4)])
89836
90071
  });
89837
90072
  if (!res.ok)
89838
90073
  throw new Error(`listMyBots ${res.status}`);
@@ -89843,6 +90078,10 @@ async function createDaemon(opts) {
89843
90078
  botsById.clear();
89844
90079
  for (const b of bots) {
89845
90080
  botsById.set(b.id, {
90081
+ runtime: b.runtime,
90082
+ modelName: b.modelName,
90083
+ reasoningEffort: b.reasoningEffort,
90084
+ runtimeConfigRevision: b.runtimeConfigRevision,
89846
90085
  name: b.name,
89847
90086
  discriminator: b.discriminator,
89848
90087
  description: b.description,
@@ -89856,12 +90095,14 @@ async function createDaemon(opts) {
89856
90095
  async function coldStartWarmup() {
89857
90096
  const start = Date.now();
89858
90097
  let attempt = 0;
89859
- while (Date.now() - start < WARMUP_CEILING_MS) {
90098
+ while (!stopping && Date.now() - start < WARMUP_CEILING_MS) {
89860
90099
  try {
89861
90100
  const bots = await listMyBotsHttp();
90101
+ if (stopping)
90102
+ return false;
89862
90103
  replaceBotCache(bots);
89863
90104
  log2.info("cold-start bot-cache warmup succeeded", { bots: bots.length, attempt });
89864
- return;
90105
+ return true;
89865
90106
  } catch {
89866
90107
  const delay3 = WARMUP_BACKOFF_MS[Math.min(attempt, WARMUP_BACKOFF_MS.length - 1)];
89867
90108
  await new Promise((r) => setTimeout(r, delay3));
@@ -89869,12 +90110,73 @@ async function createDaemon(opts) {
89869
90110
  }
89870
90111
  }
89871
90112
  log2.warn("cold-start bot-cache warmup exhausted its ceiling", { ceilingMs: WARMUP_CEILING_MS, attempts: attempt });
90113
+ return false;
90114
+ }
90115
+ async function deliverLocalMessage(agentId, message) {
90116
+ if (stopping || !botsById.has(agentId))
90117
+ return;
90118
+ const epoch = localMessageEpochs.get(agentId);
90119
+ await enrollAgent(agentId);
90120
+ const bot = botsById.get(agentId);
90121
+ if (stopping || !bot || localMessageEpochs.get(agentId) !== epoch)
90122
+ return;
90123
+ const existing = manager.snapshot().agents[agentId];
90124
+ if (message.recovery && existing) {
90125
+ clearInterruptedTurn(agentId);
90126
+ return;
90127
+ }
90128
+ if (message.recovery) {
90129
+ const record8 = interruptedTurns.find((record9) => record9.agentId === agentId);
90130
+ if (!record8 || Date.now() - record8.interruptedAt >= RECOVERY_TTL_MS) {
90131
+ clearInterruptedTurn(agentId);
90132
+ return;
90133
+ }
90134
+ clearInterruptedTurn(agentId);
90135
+ }
90136
+ if (!existing) {
90137
+ if (!bot.runtime)
90138
+ throw new Error("Bot runtime unavailable for local recovery");
90139
+ manager.register(agentId, {
90140
+ runtimeConfig: makeRuntimeConfig({
90141
+ runtime: bot.runtime,
90142
+ model: resolveModelConfig(bot.modelName ?? null),
90143
+ reasoningEffort: bot.reasoningEffort ?? undefined,
90144
+ runtimeConfigRevision: bot.runtimeConfigRevision,
90145
+ agentName: bot.name,
90146
+ agentHandle: `@${formatHandle(bot.name, bot.discriminator)}`
90147
+ }),
90148
+ launchId: randomUUID15()
90149
+ });
90150
+ }
90151
+ manager.deliver(agentId, message);
90152
+ }
90153
+ async function restoreLocalWork() {
90154
+ const [warmed] = await Promise.all([coldStartWarmup(), resyncPendingWakes()]);
90155
+ if (!warmed || stopping)
90156
+ return;
90157
+ for (const record8 of [...interruptedTurns]) {
90158
+ if (stopping)
90159
+ return;
90160
+ const age = Date.now() - record8.interruptedAt;
90161
+ if (age < 0 || age >= RECOVERY_TTL_MS || !botsById.has(record8.agentId) || manager.snapshot().agents[record8.agentId]) {
90162
+ clearInterruptedTurn(record8.agentId);
90163
+ continue;
90164
+ }
90165
+ try {
90166
+ await deliverLocalMessage(record8.agentId, interruptedTurnMessage(record8.agentId, "daemon_restart", record8.interruptedAt));
90167
+ } catch (error62) {
90168
+ log2.warn("interrupted turn recovery failed", { agentId: record8.agentId, error: String(error62) });
90169
+ }
90170
+ }
90171
+ if (!stopping)
90172
+ reminderSchedulerRef?.restore();
89872
90173
  }
89873
90174
  async function resyncPendingWakes() {
89874
90175
  try {
89875
90176
  const res = await fetch(`${opts.serverUrl}/api/community/daemon/resync-wakes`, {
89876
90177
  method: "POST",
89877
- headers: { authorization: `Bearer ${opts.machineKey}` }
90178
+ headers: { authorization: `Bearer ${opts.machineKey}` },
90179
+ signal: AbortSignal.any([stopAbort.signal, AbortSignal.timeout(1e4)])
89878
90180
  });
89879
90181
  if (!res.ok)
89880
90182
  throw new Error(`resync-wakes ${res.status}`);
@@ -90097,6 +90399,7 @@ async function createDaemon(opts) {
90097
90399
  if (info.state === "idle")
90098
90400
  refreshMachineQuota(managerRef?.agentBackendId(info.agentId) ?? undefined);
90099
90401
  if (info.state === "starting" || info.state === "running") {
90402
+ router?.markLocallyStarted(info.agentId);
90100
90403
  if (!typingHeartbeats.has(info.agentId)) {
90101
90404
  startTypingHeartbeat(info.agentId);
90102
90405
  }
@@ -90133,7 +90436,8 @@ async function createDaemon(opts) {
90133
90436
  managerRef = manager;
90134
90437
  manager.start();
90135
90438
  reminderSchedulerRef = new MessageReminderScheduler({
90136
- deliver: (agentId, message) => manager.deliver(agentId, message),
90439
+ deliver: (agentId, message) => manager.snapshot().agents[agentId] ? manager.deliver(agentId, message) : deliverLocalMessage(agentId, message),
90440
+ ...opts.daemonDir ? { filePath: join31(opts.daemonDir, "message-reminders.json") } : {},
90137
90441
  ...opts.messageReminderClock
90138
90442
  });
90139
90443
  let statusTimer = null;
@@ -90248,18 +90552,27 @@ async function createDaemon(opts) {
90248
90552
  }));
90249
90553
  channel.onWakeDesiredAdvance((cmd) => {
90250
90554
  selfSleepScheduler?.observeMessage();
90251
- reminderSchedulerRef?.observe(cmd.agentId, cmd.unreadNotice.channel, cmd.unreadNotice.latestSeq);
90555
+ try {
90556
+ reminderSchedulerRef?.observe(cmd.agentId, cmd.unreadNotice.channel, cmd.unreadNotice.latestSeq);
90557
+ } catch {
90558
+ log2.warn("reminder observation persistence failed");
90559
+ }
90252
90560
  });
90253
90561
  channel.onCommand((cmd) => {
90254
- switch (cmd.type) {
90255
- case "agent:stop":
90256
- reminderSchedulerRef?.clearAgent(cmd.agentId);
90257
- break;
90258
- case "bot:removed":
90259
- reminderSchedulerRef?.clearAgent(cmd.botId);
90260
- break;
90261
- default:
90262
- break;
90562
+ if (cmd.type !== "agent:stop" && cmd.type !== "bot:removed")
90563
+ return;
90564
+ const agentId = cmd.type === "agent:stop" ? cmd.agentId : cmd.botId;
90565
+ localMessageEpochs.set(agentId, (localMessageEpochs.get(agentId) ?? 0) + 1);
90566
+ try {
90567
+ clearInterruptedTurn(agentId);
90568
+ } catch {
90569
+ interruptedTurns = interruptedTurns.filter((record8) => record8.agentId !== agentId);
90570
+ log2.warn("interrupted turn cancellation persistence failed");
90571
+ }
90572
+ try {
90573
+ reminderSchedulerRef?.clearAgent(agentId);
90574
+ } catch {
90575
+ log2.warn("reminder cancellation persistence failed");
90263
90576
  }
90264
90577
  });
90265
90578
  channel.onCommand((cmd) => {
@@ -90285,8 +90598,7 @@ async function createDaemon(opts) {
90285
90598
  channel.onOpen(() => {
90286
90599
  if (stopping)
90287
90600
  return;
90288
- coldStartWarmup();
90289
- resyncPendingWakes();
90601
+ restoreLocalWork().catch((error62) => log2.warn("local work restore failed", { error: String(error62) }));
90290
90602
  resyncPendingDiagnostics();
90291
90603
  syncImTriggers();
90292
90604
  refreshMachineQuotas();
@@ -90319,6 +90631,20 @@ async function createDaemon(opts) {
90319
90631
  stopAbort.abort();
90320
90632
  clearInterval(quotaRefreshTimer);
90321
90633
  const failures = [];
90634
+ try {
90635
+ const saved = new Map(interruptedTurns.map((record8) => [record8.agentId, record8]));
90636
+ for (const agent of manager.interruptedTurns()) {
90637
+ saved.set(agent.agentId, {
90638
+ agentId: agent.agentId,
90639
+ sessionId: agent.sessionId,
90640
+ interruptedAt: Date.now()
90641
+ });
90642
+ }
90643
+ interruptedTurns = [...saved.values()];
90644
+ persistInterruptedTurns();
90645
+ } catch (error62) {
90646
+ failures.push(error62);
90647
+ }
90322
90648
  stopPromise = Promise.resolve().then(async () => {
90323
90649
  try {
90324
90650
  try {
@@ -90350,7 +90676,7 @@ async function createDaemon(opts) {
90350
90676
  });
90351
90677
  manager.beginShutdown();
90352
90678
  selfSleepScheduler?.stop();
90353
- reminderSchedulerRef?.clearAll();
90679
+ reminderSchedulerRef?.stop();
90354
90680
  for (const agentId of [...typingHeartbeats.keys()]) {
90355
90681
  try {
90356
90682
  emitTypingStopsAndClear(agentId);
@@ -91213,13 +91539,13 @@ import {
91213
91539
  lstatSync as lstatSync7,
91214
91540
  mkdirSync as mkdirSync13,
91215
91541
  openSync as openSync7,
91216
- readFileSync as readFileSync12,
91542
+ readFileSync as readFileSync14,
91217
91543
  readdirSync as readdirSync6,
91218
91544
  renameSync as renameSync8,
91219
91545
  unlinkSync as unlinkSync8,
91220
91546
  writeSync
91221
91547
  } from "node:fs";
91222
- import { join as join31 } from "node:path";
91548
+ import { join as join32 } from "node:path";
91223
91549
  class CoordinatorError extends Error {
91224
91550
  code;
91225
91551
  constructor(code5) {
@@ -91286,15 +91612,15 @@ function commandFrom(sidecar) {
91286
91612
  }
91287
91613
  function createDiagnosticReportCoordinator(args) {
91288
91614
  const fsOps = args.fsOps ?? defaultFsOps();
91289
- const dir = join31(args.machineDir, "diagnostics");
91615
+ const dir = join32(args.machineDir, "diagnostics");
91290
91616
  let stopped = false;
91291
91617
  let active = null;
91292
91618
  const retryCancels = new Set;
91293
91619
  const checkpoint = (point3) => {
91294
91620
  args.checkpoint?.(point3);
91295
91621
  };
91296
- const archivePath = (reportId) => join31(dir, `report-${reportId}.ndjson.gz`);
91297
- const sidecarPath = (reportId) => join31(dir, `report-${reportId}.json`);
91622
+ const archivePath = (reportId) => join32(dir, `report-${reportId}.ndjson.gz`);
91623
+ const sidecarPath = (reportId) => join32(dir, `report-${reportId}.json`);
91298
91624
  const ensureDir = () => {
91299
91625
  if (existsSync13(dir)) {
91300
91626
  const stat4 = lstatSync7(dir);
@@ -91328,7 +91654,7 @@ function createDiagnosticReportCoordinator(args) {
91328
91654
  let temp = "";
91329
91655
  let fd = null;
91330
91656
  for (let attempt = 0;attempt < 32; attempt += 1) {
91331
- temp = join31(dir, `.${sidecar.reportId}.${sidecar.phase}.${fsOps.randomSuffix()}.tmp`);
91657
+ temp = join32(dir, `.${sidecar.reportId}.${sidecar.phase}.${fsOps.randomSuffix()}.tmp`);
91332
91658
  try {
91333
91659
  fd = fsOps.open(temp, "wx", 384);
91334
91660
  break;
@@ -91358,7 +91684,7 @@ function createDiagnosticReportCoordinator(args) {
91358
91684
  const stat4 = lstatSync7(path20);
91359
91685
  if (!stat4.isFile() || stat4.isSymbolicLink())
91360
91686
  return null;
91361
- const bytes = readFileSync12(path20);
91687
+ const bytes = readFileSync14(path20);
91362
91688
  return { sizeBytes: bytes.byteLength, sha256: createHash7("sha256").update(bytes).digest("hex") };
91363
91689
  } catch {
91364
91690
  return null;
@@ -91445,7 +91771,7 @@ function createDiagnosticReportCoordinator(args) {
91445
91771
  return ready;
91446
91772
  };
91447
91773
  const buildAndCommit = async (command, collecting) => {
91448
- const temp = join31(dir, `.${command.reportId}.archive.${fsOps.randomSuffix()}.tmp`);
91774
+ const temp = join32(dir, `.${command.reportId}.archive.${fsOps.randomSuffix()}.tmp`);
91449
91775
  const artifact = await args.buildBundle({ command, outputPath: temp });
91450
91776
  checkpoint("archive_temp_written");
91451
91777
  const fd = fsOps.open(artifact.path, "r+");
@@ -91488,7 +91814,7 @@ function createDiagnosticReportCoordinator(args) {
91488
91814
  const stat4 = lstatSync7(path20);
91489
91815
  if (!stat4.isFile() || stat4.isSymbolicLink())
91490
91816
  return null;
91491
- return parseSidecar(JSON.parse(readFileSync12(path20, "utf8")));
91817
+ return parseSidecar(JSON.parse(readFileSync14(path20, "utf8")));
91492
91818
  } catch {
91493
91819
  return null;
91494
91820
  }
@@ -92126,6 +92452,7 @@ async function runPreparedDaemon(prepared, opts) {
92126
92452
  ownerToken: prepared.ownerToken
92127
92453
  }, { logger: log2 });
92128
92454
  daemon = await createDaemon({
92455
+ daemonDir: prepared.daemonDir,
92129
92456
  machineKey: prepared.machineKey,
92130
92457
  serverUrl: prepared.serverUrl,
92131
92458
  serverWsUrl: prepared.wsUrl,
@@ -93059,6 +93386,7 @@ function presentScheduleEventForAgent(event) {
93059
93386
  scheduledAt: toLocalISO(event.lastExecution.scheduledAt),
93060
93387
  status: event.lastExecution.status,
93061
93388
  ...event.lastExecution.ackedAt ? { ackedAt: toLocalISO(event.lastExecution.ackedAt) } : {},
93389
+ ...event.lastExecution.ackResult ? { ackResult: event.lastExecution.ackResult } : {},
93062
93390
  ...event.lastExecution.lastError ? { lastError: event.lastExecution.lastError } : {},
93063
93391
  updatedAt: toLocalISO(event.lastExecution.updatedAt)
93064
93392
  }
@@ -93072,7 +93400,9 @@ function presentOccurrenceForAgent(occ) {
93072
93400
  eventId: occ.eventId,
93073
93401
  startAt: toLocalISO(occ.startAt),
93074
93402
  endAt: toLocalISO(occ.endAt),
93075
- runStatus: occ.runStatus
93403
+ runStatus: occ.runStatus,
93404
+ ...occ.ackedAt ? { ackedAt: toLocalISO(occ.ackedAt) } : {},
93405
+ ...occ.ackResult ? { ackResult: occ.ackResult } : {}
93076
93406
  };
93077
93407
  }
93078
93408
  function registerScheduleCommands(program, getApi, output2) {
@@ -93118,7 +93448,7 @@ function registerScheduleCommands(program, getApi, output2) {
93118
93448
  const res = await api2.scheduleCreate(payload);
93119
93449
  output2({ success: { event: presentScheduleEventForAgent(res.event) } });
93120
93450
  });
93121
- schedule2.command("update").argument("<id>", "schedule event id (sch_...)").description("update a shared schedule event").option("--title <text>", "new title").option("--description <text>", "new instructions/context").option("--at <iso>", "new start time (ISO-8601)").option("--tz <iana>", "new IANA timezone").option("--duration <minutes>", "new duration in minutes (5-1440)").option("--repeat <freq>", "hourly, daily, weekly, monthly, or none to clear recurrence").option("--interval <n>", "recurrence interval").option("--weekdays <days>", "comma-separated weekdays for weekly repeat (0-6 or sun..sat)").option("--until <iso>", "recurrence end timestamp (ISO-8601)").option("--count <n>", "maximum total occurrences").option("--message <ref>", "rebind to another accessible message ref").option("--ack", "mark the current scheduled execution as completed").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function(id4) {
93451
+ schedule2.command("update").argument("<id>", "schedule event id (sch_...)").description("update a shared schedule event").option("--title <text>", "new title").option("--description <text>", "new instructions/context").option("--at <iso>", "new start time (ISO-8601)").option("--tz <iana>", "new IANA timezone").option("--duration <minutes>", "new duration in minutes (5-1440)").option("--repeat <freq>", "hourly, daily, weekly, monthly, or none to clear recurrence").option("--interval <n>", "recurrence interval").option("--weekdays <days>", "comma-separated weekdays for weekly repeat (0-6 or sun..sat)").option("--until <iso>", "recurrence end timestamp (ISO-8601)").option("--count <n>", "maximum total occurrences").option("--message <ref>", "rebind to another accessible message ref").option("--ack <result>", "mark the current scheduled execution as completed with a short result summary (<= 1 KiB UTF-8)").exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} }).action(async function(id4) {
93122
93452
  const opts = this.opts();
93123
93453
  const api2 = getApi();
93124
93454
  if (!api2.scheduleUpdate)
@@ -93126,6 +93456,16 @@ function registerScheduleCommands(program, getApi, output2) {
93126
93456
  if (opts.tz !== undefined && !isValidIanaTimeZone(opts.tz.trim())) {
93127
93457
  throw new Error(`invalid IANA timezone: ${opts.tz}`);
93128
93458
  }
93459
+ let ackResult;
93460
+ if (opts.ack !== undefined) {
93461
+ ackResult = opts.ack.trim();
93462
+ if (!ackResult) {
93463
+ throw new Error("--ack requires a non-empty result summary (max 1024 UTF-8 bytes)");
93464
+ }
93465
+ if (utf8ByteLength(ackResult) > SCHEDULE_ACK_RESULT_MAX_BYTES) {
93466
+ throw new Error(`--ack result summary must be at most ${SCHEDULE_ACK_RESULT_MAX_BYTES} UTF-8 bytes`);
93467
+ }
93468
+ }
93129
93469
  const recurrence = parseRecurrenceOptions(opts);
93130
93470
  const patch = ScheduleUpdateRequestSchema.parse({
93131
93471
  ...opts.title !== undefined ? { title: opts.title } : {},
@@ -93135,7 +93475,7 @@ function registerScheduleCommands(program, getApi, output2) {
93135
93475
  ...opts.duration !== undefined ? { durationMinutes: parsePositiveIntOption(opts.duration, "--duration") } : {},
93136
93476
  ...recurrence !== undefined ? { recurrence } : {},
93137
93477
  ...opts.message !== undefined ? { sourceMessageRef: opts.message } : {},
93138
- ...opts.ack ? { ack: true } : {}
93478
+ ...ackResult !== undefined ? { ack: true, ackResult } : {}
93139
93479
  });
93140
93480
  if (Object.keys(patch).length === 0) {
93141
93481
  throw new Error("provide at least one field to update");
@@ -93414,7 +93754,7 @@ function registerUseCommands(program, output2) {
93414
93754
  import { Command, CommanderError } from "commander";
93415
93755
 
93416
93756
  // src/cli/pii.ts
93417
- import { readFileSync as readFileSync15, statSync as statSync9 } from "node:fs";
93757
+ import { readFileSync as readFileSync17, statSync as statSync9 } from "node:fs";
93418
93758
  import { basename as basename7, extname as extname3 } from "node:path";
93419
93759
  function registerPiiCommands(program, output2) {
93420
93760
  const pii = program.command("pii").description("local outgoing message text filters; list or append a TypeScript plugin").exitOverride();
@@ -93425,7 +93765,7 @@ function registerPiiCommands(program, output2) {
93425
93765
  throw new Error("PII requires the running bot's local daemon proxy");
93426
93766
  const response = await fetch(`${url2.replace(/\/+$/, "")}${LOCAL_PII_PATH}`, {
93427
93767
  method: input2 ? "POST" : "GET",
93428
- headers: { authorization: `Bearer ${readFileSync15(tokenFile, "utf8").trim()}`, "content-type": "application/json" },
93768
+ headers: { authorization: `Bearer ${readFileSync17(tokenFile, "utf8").trim()}`, "content-type": "application/json" },
93429
93769
  ...input2 ? { body: JSON.stringify(input2) } : {},
93430
93770
  signal: AbortSignal.timeout(5000)
93431
93771
  });
@@ -93442,7 +93782,7 @@ function registerPiiCommands(program, output2) {
93442
93782
  const options = add.opts();
93443
93783
  if (statSync9(options.file).size > PII_SOURCE_MAX_BYTES)
93444
93784
  throw new Error("PII_SOURCE_TOO_LARGE");
93445
- await request({ action: "add", name: basename7(options.file, extname3(options.file)), description: options.description, source: readFileSync15(options.file, "utf8") });
93785
+ await request({ action: "add", name: basename7(options.file, extname3(options.file)), description: options.description, source: readFileSync17(options.file, "utf8") });
93446
93786
  });
93447
93787
  }
93448
93788
 
@@ -94067,7 +94407,7 @@ async function daemonReplace(opts) {
94067
94407
  }
94068
94408
 
94069
94409
  // src/cli/messageReminderClient.ts
94070
- import { readFileSync as readFileSync17 } from "node:fs";
94410
+ import { readFileSync as readFileSync19 } from "node:fs";
94071
94411
  var LOCAL_MESSAGE_REMINDER_PATH2 = "/__alook/local/message-reminder";
94072
94412
  var MIN_REMINDER_MS = 60000;
94073
94413
  var MAX_REMINDER_MS = 24 * 60 * 60000;
@@ -94093,7 +94433,7 @@ async function armMessageReminderFromEnv(input2, env = process.env, fetchImpl =
94093
94433
  }
94094
94434
  let voucher;
94095
94435
  try {
94096
- voucher = readFileSync17(tokenFile, "utf8").trim();
94436
+ voucher = readFileSync19(tokenFile, "utf8").trim();
94097
94437
  } catch {
94098
94438
  return { armed: false, reason: "local reminder voucher unavailable" };
94099
94439
  }