@alan-ai-hq/agent-manager-linux-arm64 0.1.192 → 0.1.194

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.
Files changed (4) hide show
  1. package/alan-agent.cjs +24320 -20665
  2. package/alan-holder.cjs +36450 -32455
  3. package/alan-lease.cjs +596 -368
  4. package/package.json +1 -1
package/alan-lease.cjs CHANGED
@@ -21093,252 +21093,6 @@ var init_agent_context = __esm({
21093
21093
  }
21094
21094
  });
21095
21095
 
21096
- // ../shared/src/runtime-v2/machine-identity.ts
21097
- var machineEndpointsSchema, machineCredentialGrantSchema, MACHINE_PATHS, machinePlatformSchema, machineRegisterRequestSchema, machineEnrollRequestSchema, machineRenewRequestSchema, machineRenewReusedSchema, deviceAuthorizationSchema, machineDeviceAuthorizationRequestSchema, machineDeviceTokenRequestSchema, machineDeviceTokenSchema, DEVICE_TOKEN_ERRORS, machineDeviceTokenErrorSchema, machineMcpCredentialRequestSchema, machineMcpCredentialSchema, runtimeReleaseSchema, machineSiblingSchema, MACHINE_SIBLINGS_LIMIT, machineSiblingsResponseSchema, runCodexCredentialSchema, runCodexCredentialRefreshRequestSchema, runProviderCredentialSchema;
21098
- var init_machine_identity = __esm({
21099
- "../shared/src/runtime-v2/machine-identity.ts"() {
21100
- "use strict";
21101
- init_zod();
21102
- init_ids();
21103
- machineEndpointsSchema = external_exports.object({
21104
- apiUrl: external_exports.url(),
21105
- wsUrl: external_exports.url()
21106
- });
21107
- machineCredentialGrantSchema = external_exports.object({
21108
- machineId: machineIdSchema,
21109
- accessToken: external_exports.string().min(1),
21110
- accessTokenExpiresAt: external_exports.iso.datetime(),
21111
- renewalToken: external_exports.string().min(1),
21112
- endpoints: machineEndpointsSchema
21113
- });
21114
- MACHINE_PATHS = {
21115
- /** POST with a one-time setup grant (what `install --setup-token` / `setup` send). */
21116
- register: "/public/machines/register",
21117
- /** POST with a cloud sandbox's one-time enrollment code from `ALAN_RUNTIME_ENROLLMENT_CODE`. */
21118
- enroll: "/public/machines/enroll",
21119
- // quirk: POST with the current renewal token; the response carries a new one and the previous one dies.
21120
- renew: "/public/machines/me/renew",
21121
- /** POST by the machine itself on logout/uninstall. */
21122
- revokeSelf: "/public/machines/me/revoke",
21123
- /** POST by a session holder: an MCP-only credential bound to one conversation. */
21124
- mcpCredential: "/public/machines/me/mcp-credential",
21125
- /** POST by the runtime for git's credential helper: a short capability for one repository. */
21126
- gitCapability: "/public/machines/me/git/capability",
21127
- /** Any method, by the runtime for `gh`: the GitHub API behind Alan's policy (`github-proxy.ts`). */
21128
- githubProxy: "/public/machines/me/github",
21129
- /**
21130
- * Device-code setup for a terminal with no browser session (`alan-agent setup --device`,
21131
- * RFC 8628). The user approves on the web page the v1 flow uses; the token route then
21132
- * hands out a one-time setup grant for `register`.
21133
- */
21134
- deviceAuthorization: "/public/machines/device-authorizations",
21135
- deviceToken: "/public/machines/device-authorizations/token",
21136
- /** What version this environment wants machines on; the shape of this path never changes. */
21137
- currentRelease: "/public/runtime/releases/v1/current",
21138
- /** GET by `doctor`: the calling machine and its owner's other machines. */
21139
- siblings: "/public/machines/me/siblings"
21140
- };
21141
- machinePlatformSchema = external_exports.object({
21142
- os: external_exports.enum(["darwin", "linux", "win32"]),
21143
- arch: external_exports.string().min(1),
21144
- hostname: external_exports.string().min(1),
21145
- runtimeVersion: external_exports.string().min(1)
21146
- });
21147
- machineRegisterRequestSchema = external_exports.object({
21148
- setupToken: external_exports.string().min(1),
21149
- platform: machinePlatformSchema,
21150
- /** Present when re-registering the same install, so the server can reuse the machine row. */
21151
- machineId: machineIdSchema.optional(),
21152
- /** Chosen by the install before its first registration, so a credential lost locally still maps to its row. */
21153
- installationId: external_exports.guid().optional()
21154
- });
21155
- machineEnrollRequestSchema = external_exports.object({ enrollmentCode: external_exports.string().min(1) });
21156
- machineRenewRequestSchema = external_exports.object({ renewalToken: external_exports.string().min(1) });
21157
- machineRenewReusedSchema = external_exports.object({
21158
- error: external_exports.literal("renewal_token_reused"),
21159
- message: external_exports.string()
21160
- });
21161
- deviceAuthorizationSchema = external_exports.object({
21162
- deviceCode: external_exports.string().min(1),
21163
- userCode: external_exports.string().min(1),
21164
- verificationUri: external_exports.url(),
21165
- intervalSeconds: external_exports.number().int().positive(),
21166
- expiresInSeconds: external_exports.number().int().positive()
21167
- });
21168
- machineDeviceAuthorizationRequestSchema = external_exports.object({
21169
- platform: machinePlatformSchema,
21170
- /** Register into this team; the approving user must have access to it in their organization. */
21171
- teamId: external_exports.guid().optional()
21172
- });
21173
- machineDeviceTokenRequestSchema = external_exports.object({ deviceCode: external_exports.string().min(1) });
21174
- machineDeviceTokenSchema = external_exports.object({ setupToken: external_exports.string().min(1) });
21175
- DEVICE_TOKEN_ERRORS = [
21176
- "authorization_pending",
21177
- "slow_down",
21178
- "expired_token",
21179
- "access_denied",
21180
- "invalid_grant"
21181
- ];
21182
- machineDeviceTokenErrorSchema = external_exports.object({ error: external_exports.enum(DEVICE_TOKEN_ERRORS) });
21183
- machineMcpCredentialRequestSchema = external_exports.object({ conversationId: conversationIdSchema });
21184
- machineMcpCredentialSchema = external_exports.object({
21185
- authorization: external_exports.string().startsWith("Bearer "),
21186
- expiresAt: external_exports.iso.datetime()
21187
- });
21188
- runtimeReleaseSchema = external_exports.object({
21189
- /** npm version of the platform packages; machines trust the tarball by the registry's integrity. */
21190
- version: external_exports.string().min(1),
21191
- /** Machines below this refuse no work but are told to upgrade; below `minimumVersion` they are refused. */
21192
- minimumVersion: external_exports.string().min(1),
21193
- /** Staged rollout: the share of machines (0\u2013100) that should take this version now. */
21194
- rolloutPercent: external_exports.number().int().min(0).max(100)
21195
- });
21196
- machineSiblingSchema = external_exports.object({
21197
- machineId: machineIdSchema,
21198
- name: external_exports.string(),
21199
- hostname: external_exports.string().nullable(),
21200
- os: external_exports.string().nullable(),
21201
- protocol: external_exports.number().int().nullable(),
21202
- online: external_exports.boolean(),
21203
- lastSeenAt: external_exports.iso.datetime().nullable(),
21204
- current: external_exports.boolean(),
21205
- /** Registered from the same install (`installationId`) as the caller. */
21206
- sameInstallation: external_exports.boolean()
21207
- });
21208
- MACHINE_SIBLINGS_LIMIT = 200;
21209
- machineSiblingsResponseSchema = external_exports.object({
21210
- machines: external_exports.array(machineSiblingSchema).max(MACHINE_SIBLINGS_LIMIT)
21211
- });
21212
- runCodexCredentialSchema = external_exports.object({
21213
- accessToken: external_exports.string().min(1),
21214
- chatgptAccountId: external_exports.string().min(1),
21215
- chatgptPlanType: external_exports.string().nullable(),
21216
- credentialId: external_exports.uuid().optional(),
21217
- providerUserId: external_exports.string().min(1).optional()
21218
- });
21219
- runCodexCredentialRefreshRequestSchema = external_exports.object({
21220
- /** sha256 hex of the access token Codex was refused with; a newer stored token is returned instead of rotating. */
21221
- rejectedAccessTokenSha256: external_exports.string().regex(/^[0-9a-f]{64}$/).optional()
21222
- });
21223
- runProviderCredentialSchema = external_exports.object({
21224
- /** Environment variables for the agent CLI, e.g. ANTHROPIC_API_KEY; empty when the CLI's own login is used. */
21225
- env: external_exports.record(external_exports.string(), external_exports.string()),
21226
- /** The bound Codex login for a cloud sandbox; absent where the CLI's own login is used. */
21227
- codex: runCodexCredentialSchema.optional()
21228
- });
21229
- }
21230
- });
21231
-
21232
- // ../shared/src/runtime-v2/query-result.ts
21233
- function queryResultSchema(value) {
21234
- return external_exports.discriminatedUnion("ok", [
21235
- external_exports.object({ ok: external_exports.literal(true), value }),
21236
- external_exports.object({ ok: external_exports.literal(false), error: queryErrorSchema })
21237
- ]);
21238
- }
21239
- var queryErrorSchema;
21240
- var init_query_result = __esm({
21241
- "../shared/src/runtime-v2/query-result.ts"() {
21242
- "use strict";
21243
- init_zod();
21244
- queryErrorSchema = external_exports.object({
21245
- code: external_exports.string().min(1),
21246
- message: external_exports.string()
21247
- });
21248
- }
21249
- });
21250
-
21251
- // ../shared/src/runtime-v2/capabilities.ts
21252
- var PROVIDER_MODELS_MAX, providerAuthStateSchema, PROVIDER_MODEL_VARIANTS_MAX, providerModelVariantSchema, providerModelBillingSchema, providerModelSchema, providerModelsSourceSchema, providerCapabilitySchema, machineFactsSchema, machineCapabilitiesSchema, modelsScanRequestSchema, modelsScanResultSchema, capabilitiesAckSchema;
21253
- var init_capabilities = __esm({
21254
- "../shared/src/runtime-v2/capabilities.ts"() {
21255
- "use strict";
21256
- init_zod();
21257
- init_machine_identity();
21258
- init_query_result();
21259
- PROVIDER_MODELS_MAX = 2e3;
21260
- providerAuthStateSchema = external_exports.enum(["signed_in", "signed_out", "unknown"]);
21261
- PROVIDER_MODEL_VARIANTS_MAX = 32;
21262
- providerModelVariantSchema = external_exports.string().min(1).max(64).regex(/^[^\s\p{Cc}]+$/u);
21263
- providerModelBillingSchema = external_exports.enum(["free", "paid"]);
21264
- providerModelSchema = external_exports.object({
21265
- id: external_exports.string().min(1).max(200),
21266
- label: external_exports.string().min(1).max(200).optional(),
21267
- /** The CLI's reasoning variants in its own order; empty when it says the model has none. */
21268
- variants: external_exports.array(providerModelVariantSchema).max(PROVIDER_MODEL_VARIANTS_MAX).optional(),
21269
- billing: providerModelBillingSchema.optional()
21270
- });
21271
- providerModelsSourceSchema = external_exports.enum(["discovered", "catalog"]);
21272
- providerCapabilitySchema = external_exports.object({
21273
- backendKind: external_exports.string().min(1).max(64),
21274
- installed: external_exports.boolean(),
21275
- version: external_exports.string().min(1).max(200).optional(),
21276
- auth: providerAuthStateSchema,
21277
- /** What the user has to do when `auth` is `signed_out`, e.g. the login command. */
21278
- authMessage: external_exports.string().min(1).max(1e3).optional(),
21279
- /** Provider-reported account tier or API-key mode; never inferred from executable presence. */
21280
- authLabel: external_exports.string().min(1).max(100).optional(),
21281
- /** Whether `--version` ran. Absent: not probed; a label, never a reason to hide the provider. */
21282
- runStatus: external_exports.enum(["ready", "cannot_start"]).optional(),
21283
- /** The CLI's own first line when it could not start. */
21284
- runMessage: external_exports.string().min(1).max(1e3).optional(),
21285
- /** Absent: the CLI has no model list the runtime can read; the server keeps its catalog. */
21286
- models: external_exports.array(providerModelSchema).max(PROVIDER_MODELS_MAX).optional(),
21287
- /** Present with `models`. */
21288
- modelsSource: providerModelsSourceSchema.optional(),
21289
- /** Ids the CLI itself marks deprecated; never in `models`. Absence is not a deprecation. */
21290
- deprecatedModels: external_exports.array(external_exports.string().min(1).max(200)).max(PROVIDER_MODELS_MAX).optional(),
21291
- /** The runtime can hand a mid-run message to the running turn. Absent: it cannot. */
21292
- steer: external_exports.boolean().optional(),
21293
- checkedAt: external_exports.number().int().nonnegative()
21294
- });
21295
- machineFactsSchema = machinePlatformSchema.extend({
21296
- osRelease: external_exports.string().min(1).max(200),
21297
- cpuCount: external_exports.number().int().nonnegative(),
21298
- totalMemoryBytes: external_exports.number().int().nonnegative()
21299
- });
21300
- machineCapabilitiesSchema = external_exports.object({
21301
- providers: external_exports.array(providerCapabilitySchema).max(64),
21302
- hasGit: external_exports.boolean(),
21303
- /**
21304
- * The runtime answers `files.*` workspace queries and pushes `workspace.changed`. Absent: an
21305
- * older runtime; the server lists and reads files through the sandbox provider instead.
21306
- */
21307
- workspaceFiles: external_exports.boolean().optional(),
21308
- machine: machineFactsSchema,
21309
- scannedAt: external_exports.number().int().nonnegative()
21310
- });
21311
- modelsScanRequestSchema = external_exports.object({ refresh: external_exports.boolean().optional() });
21312
- modelsScanResultSchema = queryResultSchema(machineCapabilitiesSchema);
21313
- capabilitiesAckSchema = external_exports.object({ stored: external_exports.boolean() });
21314
- }
21315
- });
21316
-
21317
- // ../shared/src/validators/attachments.ts
21318
- var MAX_COMMENT_ATTACHMENTS, requestPresignedUploadSchema, linkAttachmentSchema, renameAttachmentSchema;
21319
- var init_attachments = __esm({
21320
- "../shared/src/validators/attachments.ts"() {
21321
- "use strict";
21322
- init_zod();
21323
- MAX_COMMENT_ATTACHMENTS = 10;
21324
- requestPresignedUploadSchema = external_exports.object({
21325
- filename: external_exports.string().min(1).max(500),
21326
- mimeType: external_exports.string().min(1).max(200),
21327
- size: external_exports.number().int().positive().max(50 * 1024 * 1024),
21328
- // 50MB max
21329
- entityType: external_exports.string().min(1).max(50),
21330
- entityId: external_exports.uuid().optional()
21331
- });
21332
- linkAttachmentSchema = external_exports.object({
21333
- entityType: external_exports.string().min(1).max(50),
21334
- entityId: external_exports.uuid()
21335
- });
21336
- renameAttachmentSchema = external_exports.object({
21337
- displayName: external_exports.string().trim().min(1).max(500)
21338
- });
21339
- }
21340
- });
21341
-
21342
21096
  // ../shared/src/session-owned-execution.ts
21343
21097
  var EXECUTION_OWNERS;
21344
21098
  var init_session_owned_execution = __esm({
@@ -22005,6 +21759,7 @@ var init_desired_state = __esm({
22005
21759
  resumeFallbackContext: external_exports.string().optional(),
22006
21760
  projectPath: external_exports.string().min(1).optional(),
22007
21761
  workspacePathPinned: external_exports.boolean().optional(),
21762
+ projectPathFallback: external_exports.string().min(1).optional(),
22008
21763
  localWorktree: external_exports.object({ branch: gitBranchSchema, baseBranch: gitBranchSchema.optional() }).optional(),
22009
21764
  approvedWorkspacePaths: external_exports.array(external_exports.string().min(1)).optional(),
22010
21765
  repoLocalPaths: external_exports.array(repoLocalPathSchema).optional(),
@@ -22024,6 +21779,7 @@ var init_desired_state = __esm({
22024
21779
  attachments: external_exports.array(runAttachmentSchema).optional(),
22025
21780
  parsedAttachments: external_exports.array(parsedAttachmentSchema).optional(),
22026
21781
  externalMcpServers: external_exports.record(external_exports.string(), externalMcpServerSchema).optional(),
21782
+ pluginSetVersion: external_exports.string().min(1).optional(),
22027
21783
  promptContext: runPromptContextSchema.optional(),
22028
21784
  /** Absent means entitled, so a spec from an older server keeps the code-index prompts. */
22029
21785
  codeIndexEnabled: external_exports.boolean().optional(),
@@ -22036,47 +21792,205 @@ var init_desired_state = __esm({
22036
21792
  gitCoAuthor: gitCoAuthorSchema.optional()
22037
21793
  // Never here: the provider API key. The holder fetches it per run (RUN_PROVIDER_CREDENTIAL_PATH).
22038
21794
  });
22039
- desiredRunSchema = external_exports.object({
22040
- runId: runIdSchema,
22041
- conversationId: conversationIdSchema,
22042
- spec: runSpecSchema,
22043
- abortRequested: external_exports.boolean()
21795
+ desiredRunSchema = external_exports.object({
21796
+ runId: runIdSchema,
21797
+ conversationId: conversationIdSchema,
21798
+ spec: runSpecSchema,
21799
+ abortRequested: external_exports.boolean(),
21800
+ forceStopRequested: external_exports.boolean().optional()
21801
+ });
21802
+ pendingUploadSchema = external_exports.object({
21803
+ runId: runIdSchema,
21804
+ conversationId: conversationIdSchema,
21805
+ admittedOffset: external_exports.number().int().nonnegative()
21806
+ });
21807
+ STOP_RUN_IDS_LIMIT = 200;
21808
+ desiredStateSchema = external_exports.object({
21809
+ runs: external_exports.array(desiredRunSchema),
21810
+ blockedRuns: external_exports.array(
21811
+ external_exports.object({
21812
+ runId: runIdSchema,
21813
+ feature: external_exports.enum([
21814
+ "session_interaction_v1",
21815
+ "session_operations_v1",
21816
+ "session_selection_v1",
21817
+ "bounded_delegation_v1"
21818
+ ]),
21819
+ reason: external_exports.enum(["runtime_feature_unsupported", "runtime_link_not_ready"])
21820
+ })
21821
+ ).optional(),
21822
+ /** The machine's saved workspaces; replaces the previous server list on every read. */
21823
+ approvedWorkspacePaths: external_exports.array(machinePathSchema).max(2e3).optional(),
21824
+ /** Absent from an older server: the runtime then uploads only on its own doorbell. */
21825
+ pendingUploads: external_exports.array(pendingUploadSchema).optional(),
21826
+ /**
21827
+ * Runs the server ended on its own (stall ceiling, lost VM) that this machine may still hold.
21828
+ * The runtime stops any it holds unended; absence from `runs` alone never stops a run.
21829
+ */
21830
+ stopRunIds: external_exports.array(runIdSchema).max(STOP_RUN_IDS_LIMIT).optional()
21831
+ });
21832
+ }
21833
+ });
21834
+
21835
+ // ../shared/src/runtime-v2/machine-identity.ts
21836
+ var machineEndpointsSchema, machineCredentialGrantSchema, MACHINE_PATHS, machinePlatformSchema, machineRegisterRequestSchema, machineEnrollRequestSchema, machineRenewRequestSchema, machineRenewReusedSchema, deviceAuthorizationSchema, machineDeviceAuthorizationRequestSchema, machineDeviceTokenRequestSchema, machineDeviceTokenSchema, DEVICE_TOKEN_ERRORS, machineDeviceTokenErrorSchema, machineMcpCredentialRequestSchema, machineMcpCredentialSchema, runtimeReleaseSchema, machineSiblingSchema, MACHINE_SIBLINGS_LIMIT, machineSiblingsResponseSchema, runCodexCredentialSchema, runCodexCredentialRefreshRequestSchema, runProviderCredentialSchema;
21837
+ var init_machine_identity = __esm({
21838
+ "../shared/src/runtime-v2/machine-identity.ts"() {
21839
+ "use strict";
21840
+ init_zod();
21841
+ init_ids();
21842
+ machineEndpointsSchema = external_exports.object({
21843
+ apiUrl: external_exports.url(),
21844
+ wsUrl: external_exports.url(),
21845
+ gitEgressUrl: external_exports.url().optional()
21846
+ });
21847
+ machineCredentialGrantSchema = external_exports.object({
21848
+ machineId: machineIdSchema,
21849
+ accessToken: external_exports.string().min(1),
21850
+ accessTokenExpiresAt: external_exports.iso.datetime(),
21851
+ renewalToken: external_exports.string().min(1),
21852
+ endpoints: machineEndpointsSchema
21853
+ });
21854
+ MACHINE_PATHS = {
21855
+ /** POST with a one-time setup grant (what `install --setup-token` / `setup` send). */
21856
+ register: "/public/machines/register",
21857
+ /** POST with a cloud sandbox's one-time enrollment code from `ALAN_RUNTIME_ENROLLMENT_CODE`. */
21858
+ enroll: "/public/machines/enroll",
21859
+ // quirk: POST with the current renewal token; the response carries a new one and the previous one dies.
21860
+ renew: "/public/machines/me/renew",
21861
+ /** POST by the machine itself on logout/uninstall. */
21862
+ revokeSelf: "/public/machines/me/revoke",
21863
+ /** POST by a session holder: an MCP-only credential bound to one conversation. */
21864
+ mcpCredential: "/public/machines/me/mcp-credential",
21865
+ backgroundRun: "/public/machines/me/background-runs",
21866
+ /** POST by the runtime for git's credential helper: a short capability for one repository. */
21867
+ gitCapability: "/public/machines/me/git/capability",
21868
+ /** Any method, by the runtime for `gh`: the GitHub API behind Alan's policy (`github-proxy.ts`). */
21869
+ githubProxy: "/public/machines/me/github",
21870
+ /**
21871
+ * Device-code setup for a terminal with no browser session (`alan-agent setup --device`,
21872
+ * RFC 8628). The user approves on the web page the v1 flow uses; the token route then
21873
+ * hands out a one-time setup grant for `register`.
21874
+ */
21875
+ deviceAuthorization: "/public/machines/device-authorizations",
21876
+ deviceToken: "/public/machines/device-authorizations/token",
21877
+ /** What version this environment wants machines on; the shape of this path never changes. */
21878
+ currentRelease: "/public/runtime/releases/v1/current",
21879
+ /** GET by `doctor`: the calling machine and its owner's other machines. */
21880
+ siblings: "/public/machines/me/siblings"
21881
+ };
21882
+ machinePlatformSchema = external_exports.object({
21883
+ os: external_exports.enum(["darwin", "linux", "win32"]),
21884
+ arch: external_exports.string().min(1),
21885
+ hostname: external_exports.string().min(1),
21886
+ runtimeVersion: external_exports.string().min(1)
21887
+ });
21888
+ machineRegisterRequestSchema = external_exports.object({
21889
+ setupToken: external_exports.string().min(1),
21890
+ platform: machinePlatformSchema,
21891
+ /** Present when re-registering the same install, so the server can reuse the machine row. */
21892
+ machineId: machineIdSchema.optional(),
21893
+ /** Chosen by the install before its first registration, so a credential lost locally still maps to its row. */
21894
+ installationId: external_exports.guid().optional()
21895
+ });
21896
+ machineEnrollRequestSchema = external_exports.object({ enrollmentCode: external_exports.string().min(1) });
21897
+ machineRenewRequestSchema = external_exports.object({ renewalToken: external_exports.string().min(1) });
21898
+ machineRenewReusedSchema = external_exports.object({
21899
+ error: external_exports.literal("renewal_token_reused"),
21900
+ message: external_exports.string()
21901
+ });
21902
+ deviceAuthorizationSchema = external_exports.object({
21903
+ deviceCode: external_exports.string().min(1),
21904
+ userCode: external_exports.string().min(1),
21905
+ verificationUri: external_exports.url(),
21906
+ intervalSeconds: external_exports.number().int().positive(),
21907
+ expiresInSeconds: external_exports.number().int().positive()
21908
+ });
21909
+ machineDeviceAuthorizationRequestSchema = external_exports.object({
21910
+ platform: machinePlatformSchema,
21911
+ /** Register into this team; the approving user must have access to it in their organization. */
21912
+ teamId: external_exports.guid().optional()
21913
+ });
21914
+ machineDeviceTokenRequestSchema = external_exports.object({ deviceCode: external_exports.string().min(1) });
21915
+ machineDeviceTokenSchema = external_exports.object({ setupToken: external_exports.string().min(1) });
21916
+ DEVICE_TOKEN_ERRORS = [
21917
+ "authorization_pending",
21918
+ "slow_down",
21919
+ "expired_token",
21920
+ "access_denied",
21921
+ "invalid_grant"
21922
+ ];
21923
+ machineDeviceTokenErrorSchema = external_exports.object({ error: external_exports.enum(DEVICE_TOKEN_ERRORS) });
21924
+ machineMcpCredentialRequestSchema = external_exports.object({ conversationId: conversationIdSchema });
21925
+ machineMcpCredentialSchema = external_exports.object({
21926
+ authorization: external_exports.string().startsWith("Bearer "),
21927
+ expiresAt: external_exports.iso.datetime()
21928
+ });
21929
+ runtimeReleaseSchema = external_exports.object({
21930
+ /** npm version of the platform packages; machines trust the tarball by the registry's integrity. */
21931
+ version: external_exports.string().min(1),
21932
+ /** Machines below this refuse no work but are told to upgrade; below `minimumVersion` they are refused. */
21933
+ minimumVersion: external_exports.string().min(1),
21934
+ /** Staged rollout: the share of machines (0\u2013100) that should take this version now. */
21935
+ rolloutPercent: external_exports.number().int().min(0).max(100)
21936
+ });
21937
+ machineSiblingSchema = external_exports.object({
21938
+ machineId: machineIdSchema,
21939
+ name: external_exports.string(),
21940
+ hostname: external_exports.string().nullable(),
21941
+ os: external_exports.string().nullable(),
21942
+ protocol: external_exports.number().int().nullable(),
21943
+ online: external_exports.boolean(),
21944
+ lastSeenAt: external_exports.iso.datetime().nullable(),
21945
+ current: external_exports.boolean(),
21946
+ /** Registered from the same install (`installationId`) as the caller. */
21947
+ sameInstallation: external_exports.boolean()
21948
+ });
21949
+ MACHINE_SIBLINGS_LIMIT = 200;
21950
+ machineSiblingsResponseSchema = external_exports.object({
21951
+ machines: external_exports.array(machineSiblingSchema).max(MACHINE_SIBLINGS_LIMIT)
21952
+ });
21953
+ runCodexCredentialSchema = external_exports.object({
21954
+ accessToken: external_exports.string().min(1),
21955
+ chatgptAccountId: external_exports.string().min(1),
21956
+ chatgptPlanType: external_exports.string().nullable(),
21957
+ credentialId: external_exports.uuid().optional(),
21958
+ providerUserId: external_exports.string().min(1).optional()
21959
+ });
21960
+ runCodexCredentialRefreshRequestSchema = external_exports.object({
21961
+ /** sha256 hex of the access token Codex was refused with; a newer stored token is returned instead of rotating. */
21962
+ rejectedAccessTokenSha256: external_exports.string().regex(/^[0-9a-f]{64}$/).optional()
22044
21963
  });
22045
- pendingUploadSchema = external_exports.object({
22046
- runId: runIdSchema,
22047
- conversationId: conversationIdSchema,
22048
- admittedOffset: external_exports.number().int().nonnegative()
21964
+ runProviderCredentialSchema = external_exports.object({
21965
+ /** Environment variables for the agent CLI, e.g. ANTHROPIC_API_KEY; empty when the CLI's own login is used. */
21966
+ env: external_exports.record(external_exports.string(), external_exports.string()),
21967
+ /** The bound Codex login for a cloud sandbox; absent where the CLI's own login is used. */
21968
+ codex: runCodexCredentialSchema.optional()
22049
21969
  });
22050
- STOP_RUN_IDS_LIMIT = 200;
22051
- desiredStateSchema = external_exports.object({
22052
- runs: external_exports.array(desiredRunSchema),
22053
- blockedRuns: external_exports.array(
22054
- external_exports.object({
22055
- runId: runIdSchema,
22056
- feature: external_exports.enum([
22057
- "session_interaction_v1",
22058
- "session_operations_v1",
22059
- "session_selection_v1",
22060
- "bounded_delegation_v1"
22061
- ]),
22062
- reason: external_exports.enum(["runtime_feature_unsupported", "runtime_link_not_ready"])
22063
- })
22064
- ).optional(),
22065
- /** The machine's saved workspaces; replaces the previous server list on every read. */
22066
- approvedWorkspacePaths: external_exports.array(machinePathSchema).max(2e3).optional(),
22067
- /** Absent from an older server: the runtime then uploads only on its own doorbell. */
22068
- pendingUploads: external_exports.array(pendingUploadSchema).optional(),
22069
- /**
22070
- * Runs the server ended on its own (stall ceiling, lost VM) that this machine may still hold.
22071
- * The runtime stops any it holds unended; absence from `runs` alone never stops a run.
22072
- */
22073
- stopRunIds: external_exports.array(runIdSchema).max(STOP_RUN_IDS_LIMIT).optional()
21970
+ }
21971
+ });
21972
+
21973
+ // ../shared/src/runtime-v2/query-result.ts
21974
+ function queryResultSchema(value) {
21975
+ return external_exports.discriminatedUnion("ok", [
21976
+ external_exports.object({ ok: external_exports.literal(true), value }),
21977
+ external_exports.object({ ok: external_exports.literal(false), error: queryErrorSchema })
21978
+ ]);
21979
+ }
21980
+ var queryErrorSchema;
21981
+ var init_query_result = __esm({
21982
+ "../shared/src/runtime-v2/query-result.ts"() {
21983
+ "use strict";
21984
+ init_zod();
21985
+ queryErrorSchema = external_exports.object({
21986
+ code: external_exports.string().min(1),
21987
+ message: external_exports.string()
22074
21988
  });
22075
21989
  }
22076
21990
  });
22077
21991
 
22078
21992
  // ../shared/src/runtime-v2/link.ts
22079
- var LINK_PROTOCOL, linkHandshakeSchema, linkAuthSchema, heldRunStateSchema, heldRunSchema, helloSchema, helloAckSchema, pokeReasonSchema, prewarmPokeSchema, pokeSchema, RUN_ANSWER_MAX_LENGTH, toolCallIdSchema, runAnswerSchema, runRespondRequestSchema, runRespondStatusSchema, runRespondResultSchema, runSteerRequestSchema, runSteerStatusSchema, runSteerResultSchema, backgroundTaskIdSchema, runStopTaskRequestSchema, backgroundTaskStopResultSchema, runStopTaskResultSchema, LINK_CONNECT_ERROR_CODES, linkConnectErrorSchema, LINK_FAILURE_REASONS;
21993
+ var LINK_PROTOCOL, linkHandshakeSchema, linkAuthSchema, heldRunStateSchema, heldRunSchema, PROJECT_PATH_FALLBACK_FEATURE, helloSchema, helloAckSchema, pokeReasonSchema, prewarmPokeSchema, desiredPokeSchema, pokeSchema, RUN_ANSWER_MAX_LENGTH, toolCallIdSchema, runAnswerSchema, runRespondRequestSchema, runRespondStatusSchema, runRespondResultSchema, runSteerRequestSchema, runSteerStatusSchema, runSteerResultSchema, backgroundTaskIdSchema, runStopTaskRequestSchema, backgroundTaskStopResultSchema, runStopTaskResultSchema, LINK_CONNECT_ERROR_CODES, linkConnectErrorSchema, LINK_FAILURE_REASONS;
22080
21994
  var init_link = __esm({
22081
21995
  "../shared/src/runtime-v2/link.ts"() {
22082
21996
  "use strict";
@@ -22102,6 +22016,7 @@ var init_link = __esm({
22102
22016
  state: heldRunStateSchema,
22103
22017
  loggedBytes: byteOffsetSchema
22104
22018
  });
22019
+ PROJECT_PATH_FALLBACK_FEATURE = "project_path_fallback_v1";
22105
22020
  helloSchema = external_exports.object({
22106
22021
  epoch: external_exports.number().int().positive(),
22107
22022
  runs: external_exports.array(heldRunSchema),
@@ -22132,7 +22047,16 @@ var init_link = __esm({
22132
22047
  reason: external_exports.literal("prewarm"),
22133
22048
  conversationId: conversationIdSchema
22134
22049
  });
22135
- pokeSchema = external_exports.union([external_exports.object({ reason: pokeReasonSchema }), prewarmPokeSchema]);
22050
+ desiredPokeSchema = external_exports.object({
22051
+ reason: external_exports.literal("desired_changed"),
22052
+ desired: desiredStateSchema,
22053
+ etag: external_exports.string().min(1).max(200)
22054
+ });
22055
+ pokeSchema = external_exports.union([
22056
+ desiredPokeSchema,
22057
+ external_exports.object({ reason: pokeReasonSchema }),
22058
+ prewarmPokeSchema
22059
+ ]);
22136
22060
  RUN_ANSWER_MAX_LENGTH = 1e5;
22137
22061
  toolCallIdSchema = external_exports.string().min(1).max(1e3);
22138
22062
  runAnswerSchema = external_exports.string().max(RUN_ANSWER_MAX_LENGTH);
@@ -22207,6 +22131,119 @@ var init_link = __esm({
22207
22131
  }
22208
22132
  });
22209
22133
 
22134
+ // ../shared/src/runtime-v2/background-run.ts
22135
+ var backgroundRunRequestSchema, backgroundRunGrantSchema;
22136
+ var init_background_run = __esm({
22137
+ "../shared/src/runtime-v2/background-run.ts"() {
22138
+ "use strict";
22139
+ init_zod();
22140
+ init_desired_state();
22141
+ init_ids();
22142
+ init_link();
22143
+ backgroundRunRequestSchema = external_exports.strictObject({
22144
+ conversationId: conversationIdSchema,
22145
+ providerSessionId: external_exports.string().min(1).optional(),
22146
+ taskId: backgroundTaskIdSchema.optional(),
22147
+ idempotencyKey: external_exports.string().min(1).max(128)
22148
+ });
22149
+ backgroundRunGrantSchema = external_exports.strictObject({
22150
+ runId: runIdSchema,
22151
+ spec: runSpecSchema
22152
+ });
22153
+ }
22154
+ });
22155
+
22156
+ // ../shared/src/runtime-v2/capabilities.ts
22157
+ var PROVIDER_MODELS_MAX, providerAuthStateSchema, PROVIDER_MODEL_VARIANTS_MAX, providerModelVariantSchema, providerModelBillingSchema, providerModelSchema, providerModelsSourceSchema, providerCapabilitySchema, machineFactsSchema, machineCapabilitiesSchema, modelsScanRequestSchema, modelsScanResultSchema, capabilitiesAckSchema;
22158
+ var init_capabilities = __esm({
22159
+ "../shared/src/runtime-v2/capabilities.ts"() {
22160
+ "use strict";
22161
+ init_zod();
22162
+ init_machine_identity();
22163
+ init_query_result();
22164
+ PROVIDER_MODELS_MAX = 2e3;
22165
+ providerAuthStateSchema = external_exports.enum(["signed_in", "signed_out", "unknown"]);
22166
+ PROVIDER_MODEL_VARIANTS_MAX = 32;
22167
+ providerModelVariantSchema = external_exports.string().min(1).max(64).regex(/^[^\s\p{Cc}]+$/u);
22168
+ providerModelBillingSchema = external_exports.enum(["free", "paid"]);
22169
+ providerModelSchema = external_exports.object({
22170
+ id: external_exports.string().min(1).max(200),
22171
+ label: external_exports.string().min(1).max(200).optional(),
22172
+ /** The CLI's reasoning variants in its own order; empty when it says the model has none. */
22173
+ variants: external_exports.array(providerModelVariantSchema).max(PROVIDER_MODEL_VARIANTS_MAX).optional(),
22174
+ billing: providerModelBillingSchema.optional()
22175
+ });
22176
+ providerModelsSourceSchema = external_exports.enum(["discovered", "catalog"]);
22177
+ providerCapabilitySchema = external_exports.object({
22178
+ backendKind: external_exports.string().min(1).max(64),
22179
+ installed: external_exports.boolean(),
22180
+ version: external_exports.string().min(1).max(200).optional(),
22181
+ auth: providerAuthStateSchema,
22182
+ /** What the user has to do when `auth` is `signed_out`, e.g. the login command. */
22183
+ authMessage: external_exports.string().min(1).max(1e3).optional(),
22184
+ /** Provider-reported account tier or API-key mode; never inferred from executable presence. */
22185
+ authLabel: external_exports.string().min(1).max(100).optional(),
22186
+ /** Whether `--version` ran. Absent: not probed; a label, never a reason to hide the provider. */
22187
+ runStatus: external_exports.enum(["ready", "cannot_start"]).optional(),
22188
+ /** The CLI's own first line when it could not start. */
22189
+ runMessage: external_exports.string().min(1).max(1e3).optional(),
22190
+ /** Absent: the CLI has no model list the runtime can read; the server keeps its catalog. */
22191
+ models: external_exports.array(providerModelSchema).max(PROVIDER_MODELS_MAX).optional(),
22192
+ /** Present with `models`. */
22193
+ modelsSource: providerModelsSourceSchema.optional(),
22194
+ /** Ids the CLI itself marks deprecated; never in `models`. Absence is not a deprecation. */
22195
+ deprecatedModels: external_exports.array(external_exports.string().min(1).max(200)).max(PROVIDER_MODELS_MAX).optional(),
22196
+ /** The runtime can hand a mid-run message to the running turn. Absent: it cannot. */
22197
+ steer: external_exports.boolean().optional(),
22198
+ checkedAt: external_exports.number().int().nonnegative()
22199
+ });
22200
+ machineFactsSchema = machinePlatformSchema.extend({
22201
+ osRelease: external_exports.string().min(1).max(200),
22202
+ cpuCount: external_exports.number().int().nonnegative(),
22203
+ totalMemoryBytes: external_exports.number().int().nonnegative()
22204
+ });
22205
+ machineCapabilitiesSchema = external_exports.object({
22206
+ providers: external_exports.array(providerCapabilitySchema).max(64),
22207
+ hasGit: external_exports.boolean(),
22208
+ /**
22209
+ * The runtime answers `files.*` workspace queries and pushes `workspace.changed`. Absent: an
22210
+ * older runtime; the server lists and reads files through the sandbox provider instead.
22211
+ */
22212
+ workspaceFiles: external_exports.boolean().optional(),
22213
+ machine: machineFactsSchema,
22214
+ scannedAt: external_exports.number().int().nonnegative()
22215
+ });
22216
+ modelsScanRequestSchema = external_exports.object({ refresh: external_exports.boolean().optional() });
22217
+ modelsScanResultSchema = queryResultSchema(machineCapabilitiesSchema);
22218
+ capabilitiesAckSchema = external_exports.object({ stored: external_exports.boolean() });
22219
+ }
22220
+ });
22221
+
22222
+ // ../shared/src/validators/attachments.ts
22223
+ var MAX_COMMENT_ATTACHMENTS, requestPresignedUploadSchema, linkAttachmentSchema, renameAttachmentSchema;
22224
+ var init_attachments = __esm({
22225
+ "../shared/src/validators/attachments.ts"() {
22226
+ "use strict";
22227
+ init_zod();
22228
+ MAX_COMMENT_ATTACHMENTS = 10;
22229
+ requestPresignedUploadSchema = external_exports.object({
22230
+ filename: external_exports.string().min(1).max(500),
22231
+ mimeType: external_exports.string().min(1).max(200),
22232
+ size: external_exports.number().int().positive().max(50 * 1024 * 1024),
22233
+ // 50MB max
22234
+ entityType: external_exports.string().min(1).max(50),
22235
+ entityId: external_exports.uuid().optional()
22236
+ });
22237
+ linkAttachmentSchema = external_exports.object({
22238
+ entityType: external_exports.string().min(1).max(50),
22239
+ entityId: external_exports.uuid()
22240
+ });
22241
+ renameAttachmentSchema = external_exports.object({
22242
+ displayName: external_exports.string().trim().min(1).max(500)
22243
+ });
22244
+ }
22245
+ });
22246
+
22210
22247
  // ../shared/src/agent/problem.ts
22211
22248
  var ALAN_PROBLEM_SEVERITIES, ALAN_PROBLEM_RECOVERY_MODES, AGENT_CLI_PROBLEM_PHASES, AGENT_CLI_PROBLEM_FINALITIES, AGENT_CLI_OUTCOME_CERTAINTIES, AGENT_CLI_RETRY_OWNERS, APPLICATION_PROBLEM_PHASES, APPLICATION_PROBLEM_TRANSPORT_KINDS, AGENT_CLI_PROBLEM_CODES, APPLICATION_PROBLEM_CODES, alanProblemScopeSchema, alanProblemRecoverySchema, alanProblemBaseShape, agentCliProblemOriginSchema, agentCliProblemLifecycleSchema, agentCliProblemNativeSchema, agentCliProblemV1Schema, applicationProblemOriginSchema, applicationProblemTransportSchema, applicationProblemV1Schema, alanProblemV1Schema;
22212
22249
  var init_problem = __esm({
@@ -22464,7 +22501,7 @@ var init_agent_runs_contracts = __esm({
22464
22501
  });
22465
22502
 
22466
22503
  // ../shared/src/runtime-v2/run-log.ts
22467
- var RUN_LOG_PROTOCOL, RUN_LOG_PROTOCOL_HEADER, RUN_STEERS_MAX, runAcceptedUpdateSchema, runStartedUpdateSchema, runCodexRateLimitsUpdateSchema, runWorkspaceRelocatedUpdateSchema, gitShaSchema2, gitRefNameSchema, runGitRepositoryStateSchema, RUN_GIT_STATE_MAX_REPOSITORIES, runGitStateUpdateSchema, runOutcomeSchema, runRejectionCodeSchema, runEndedUpdateSchema, runLifecycleUpdateSchema, runLogRecordSchema;
22504
+ var RUN_LOG_PROTOCOL, RUN_LOG_PROTOCOL_HEADER, RUN_STEERS_MAX, runAcceptedUpdateSchema, runStartedUpdateSchema, runCodexRateLimitsUpdateSchema, runWorkspaceRelocatedUpdateSchema, gitShaSchema2, gitRefNameSchema, runGitRepositoryStateSchema, RUN_GIT_STATE_MAX_REPOSITORIES, runGitStateUpdateSchema, epochMsSchema, runSessionStartSchema, runTimingUpdateSchema, runOutcomeSchema, runRejectionCodeSchema, runEndedUpdateSchema, runLifecycleUpdateSchema, runLogRecordSchema;
22468
22505
  var init_run_log = __esm({
22469
22506
  "../shared/src/runtime-v2/run-log.ts"() {
22470
22507
  "use strict";
@@ -22527,6 +22564,18 @@ var init_run_log = __esm({
22527
22564
  sessionUpdate: external_exports.literal("_alan/run.git_state"),
22528
22565
  repositories: external_exports.array(runGitRepositoryStateSchema).max(RUN_GIT_STATE_MAX_REPOSITORIES)
22529
22566
  });
22567
+ epochMsSchema = external_exports.number().int().nonnegative();
22568
+ runSessionStartSchema = external_exports.enum(["reused", "opened", "respawned"]);
22569
+ runTimingUpdateSchema = external_exports.object({
22570
+ sessionUpdate: external_exports.literal("_alan/run.timing"),
22571
+ session: runSessionStartSchema,
22572
+ acceptedAt: epochMsSchema,
22573
+ admittedAt: epochMsSchema.optional(),
22574
+ inputsReadyAt: epochMsSchema,
22575
+ sessionReadyAt: epochMsSchema,
22576
+ contextReadyAt: epochMsSchema,
22577
+ turnSentAt: epochMsSchema
22578
+ });
22530
22579
  runOutcomeSchema = external_exports.enum(agentRunOutcomeEnum);
22531
22580
  runRejectionCodeSchema = external_exports.enum([
22532
22581
  "capacity",
@@ -22656,7 +22705,7 @@ var init_session_presentation = __esm({
22656
22705
  });
22657
22706
 
22658
22707
  // ../shared/src/runtime-v2/local-sessions.ts
22659
- var MAX_SESSION_SUBMISSION_BYTES, localSessionIdSchema, sessionRequestIdSchema, sessionCursorSchema, label, workspaceSchema, sessionQueueStateSchema, sessionCommandNameSchema, localSessionCapabilitiesSchema, localSessionSchema, createSessionRequestSchema, createSessionResponseSchema, sessionAttachmentReferenceSchema, stageSessionAttachmentRequestSchema, submitSessionRequestSchema, sessionRequestBindingSchema, sessionRequestReceiptSchema, sessionSnapshotSchema, sessionFeedQuerySchema, listSessionsResponseSchema, withdrawSessionRequestSchema, respondToSessionRequestSchema, sessionCommandRequestSchema, sessionControlResponseSchema, textContentSchema, contentSchema, toolContentSchema, publicSessionUpdateSchema, localSessionUpdateSchema, localSessionRecordSchema, sessionFollowFrameSchema, localSessionRouteActionSchema;
22708
+ var MAX_SESSION_SUBMISSION_BYTES, localSessionIdSchema, sessionRequestIdSchema, sessionCursorSchema, label, workspaceSchema, sessionQueueStateSchema, sessionCommandNameSchema, localSessionCapabilitiesSchema, localSessionSchema, createSessionRequestSchema, createSessionResponseSchema, sessionAttachmentReferenceSchema, stageSessionAttachmentRequestSchema, submitSessionRequestSchema, sessionRequestBindingSchema, sessionRequestReceiptSchema, sessionSnapshotSchema, sessionFeedQuerySchema, listSessionsResponseSchema, withdrawSessionRequestSchema, moveSessionRequestSchema, respondToSessionRequestSchema, sessionCommandRequestSchema, sessionControlResponseSchema, textContentSchema, contentSchema, toolContentSchema, publicSessionUpdateSchema, localSessionUpdateSchema, localSessionRecordSchema, sessionFollowFrameSchema, localSessionRouteActionSchema;
22660
22709
  var init_local_sessions = __esm({
22661
22710
  "../shared/src/runtime-v2/local-sessions.ts"() {
22662
22711
  "use strict";
@@ -22798,6 +22847,10 @@ var init_local_sessions = __esm({
22798
22847
  withdrawSessionRequestSchema = external_exports.strictObject({
22799
22848
  requestId: sessionRequestIdSchema
22800
22849
  });
22850
+ moveSessionRequestSchema = external_exports.strictObject({
22851
+ requestId: sessionRequestIdSchema,
22852
+ direction: external_exports.enum(["up", "down"])
22853
+ });
22801
22854
  respondToSessionRequestSchema = external_exports.strictObject({
22802
22855
  requestId: sessionRequestIdSchema,
22803
22856
  runId: runIdSchema,
@@ -22993,6 +23046,7 @@ var init_local_sessions = __esm({
22993
23046
  "submit",
22994
23047
  "stage",
22995
23048
  "withdraw",
23049
+ "move",
22996
23050
  "respond",
22997
23051
  "command",
22998
23052
  "stream"
@@ -23382,7 +23436,8 @@ var init_holder_protocol = __esm({
23382
23436
  type: external_exports.literal("abort"),
23383
23437
  id: external_exports.string().min(1),
23384
23438
  runId: runIdSchema,
23385
- outcome: holderAbortOutcomeSchema.optional()
23439
+ outcome: holderAbortOutcomeSchema.optional(),
23440
+ force: external_exports.boolean().optional()
23386
23441
  }),
23387
23442
  external_exports.object({ type: external_exports.literal("status"), id: external_exports.string().min(1) }),
23388
23443
  external_exports.object({ type: external_exports.literal("suspend"), id: external_exports.string().min(1) }),
@@ -23571,7 +23626,8 @@ var init_run_log_upload = __esm({
23571
23626
  admittedOffset: offsetSchema,
23572
23627
  committedOffset: offsetSchema,
23573
23628
  finalOffset: offsetSchema.nullable(),
23574
- finalized: external_exports.boolean()
23629
+ finalized: external_exports.boolean(),
23630
+ watched: external_exports.boolean().optional()
23575
23631
  });
23576
23632
  runLogUploadResponseSchema = external_exports.object({
23577
23633
  receipt: runLogUploadReceiptSchema.nullable()
@@ -23939,6 +23995,7 @@ var init_runtime_v2 = __esm({
23939
23995
  "use strict";
23940
23996
  init_activity_lease();
23941
23997
  init_agent_context();
23998
+ init_background_run();
23942
23999
  init_capabilities();
23943
24000
  init_cloud_sessions();
23944
24001
  init_commit_attribution();
@@ -23991,6 +24048,14 @@ var init_fault = __esm({
23991
24048
  });
23992
24049
 
23993
24050
  // src/kernel/clock.ts
24051
+ async function sleepUnlessAborted(clock, ms, signal) {
24052
+ try {
24053
+ await clock.sleep(ms, signal);
24054
+ return true;
24055
+ } catch {
24056
+ return false;
24057
+ }
24058
+ }
23994
24059
  var import_node_perf_hooks, import_promises, systemClock;
23995
24060
  var init_clock = __esm({
23996
24061
  "src/kernel/clock.ts"() {
@@ -24014,6 +24079,29 @@ var init_clock = __esm({
24014
24079
  }
24015
24080
  });
24016
24081
 
24082
+ // src/kernel/coalesce.ts
24083
+ function createCoalescer(clock, windowMs, run, signal) {
24084
+ let open2 = false;
24085
+ const wait = async () => {
24086
+ if (!await sleepUnlessAborted(clock, windowMs, signal)) return;
24087
+ open2 = false;
24088
+ await run().catch(() => void 0);
24089
+ };
24090
+ return {
24091
+ request: () => {
24092
+ if (open2 || signal.aborted) return;
24093
+ open2 = true;
24094
+ void wait();
24095
+ }
24096
+ };
24097
+ }
24098
+ var init_coalesce = __esm({
24099
+ "src/kernel/coalesce.ts"() {
24100
+ "use strict";
24101
+ init_clock();
24102
+ }
24103
+ });
24104
+
24017
24105
  // src/kernel/json-file.ts
24018
24106
  async function readJsonFile(path, schema) {
24019
24107
  let text;
@@ -24085,14 +24173,35 @@ function createLog(level, clock, sink) {
24085
24173
  error: (event, fields) => emit("error", event, fields)
24086
24174
  };
24087
24175
  }
24088
- function openFileLog(path, level, clock) {
24176
+ function rotateLogFiles(path, kept) {
24177
+ (0, import_node_fs.rmSync)(`${path}.${kept}`, { force: true });
24178
+ for (let index = kept - 1; index >= 1; index -= 1) {
24179
+ if ((0, import_node_fs.existsSync)(`${path}.${index}`)) (0, import_node_fs.renameSync)(`${path}.${index}`, `${path}.${index + 1}`);
24180
+ }
24181
+ (0, import_node_fs.renameSync)(path, `${path}.1`);
24182
+ }
24183
+ function openFileLog(path, level, clock, { maxBytes = MAX_LOG_FILE_BYTES, kept = KEPT_LOG_FILES } = {}) {
24089
24184
  (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path), { recursive: true, mode: 448 });
24090
- const fd = (0, import_node_fs.openSync)(path, "a", 384);
24185
+ let fd = (0, import_node_fs.openSync)(path, "a", 384);
24186
+ let bytes = (0, import_node_fs.fstatSync)(fd).size;
24091
24187
  let closed = false;
24092
24188
  const log = createLog(level, clock, (entry) => {
24093
24189
  if (closed) return;
24094
- (0, import_node_fs.writeSync)(fd, `${JSON.stringify(entry)}
24190
+ const line = `${JSON.stringify(entry)}
24191
+ `;
24192
+ if (bytes > 0 && bytes + line.length > maxBytes) {
24193
+ (0, import_node_fs.closeSync)(fd);
24194
+ try {
24195
+ rotateLogFiles(path, kept);
24196
+ bytes = 0;
24197
+ } catch (error62) {
24198
+ process.stderr.write(`log rotation failed: ${String(error62)}
24095
24199
  `);
24200
+ } finally {
24201
+ fd = (0, import_node_fs.openSync)(path, "a", 384);
24202
+ }
24203
+ }
24204
+ bytes += (0, import_node_fs.writeSync)(fd, line);
24096
24205
  });
24097
24206
  return {
24098
24207
  ...log,
@@ -24103,7 +24212,7 @@ function openFileLog(path, level, clock) {
24103
24212
  }
24104
24213
  };
24105
24214
  }
24106
- var import_node_fs, import_node_path, LEVEL_RANK, REDACTED, MAX_DEPTH, SENSITIVE_KEY, BEARER_IN_STRING, TOKEN_IN_STRING;
24215
+ var import_node_fs, import_node_path, LEVEL_RANK, REDACTED, MAX_DEPTH, SENSITIVE_KEY, BEARER_IN_STRING, TOKEN_IN_STRING, MAX_LOG_FILE_BYTES, KEPT_LOG_FILES;
24107
24216
  var init_log = __esm({
24108
24217
  "src/kernel/log.ts"() {
24109
24218
  "use strict";
@@ -24120,6 +24229,8 @@ var init_log = __esm({
24120
24229
  SENSITIVE_KEY = /(^authorization$|^cookie$|^setcookie$|password$|secret$|token$|apikey$|privatekey$|credentials?$)/;
24121
24230
  BEARER_IN_STRING = /Bearer\s+[A-Za-z0-9._~+/-]+=*/g;
24122
24231
  TOKEN_IN_STRING = /\b(?:eyJ[A-Za-z0-9_-]{20,}(?:\.[A-Za-z0-9_-]+){1,2}|(?:alan|aiden)_[A-Za-z0-9_]{16,}|sk-ant-[A-Za-z0-9_-]{16,})\b/g;
24232
+ MAX_LOG_FILE_BYTES = 10 * 1024 * 1024;
24233
+ KEPT_LOG_FILES = 3;
24123
24234
  }
24124
24235
  });
24125
24236
 
@@ -24173,6 +24284,7 @@ var init_kernel = __esm({
24173
24284
  "src/kernel/index.ts"() {
24174
24285
  "use strict";
24175
24286
  init_clock();
24287
+ init_coalesce();
24176
24288
  init_fault();
24177
24289
  init_json_file();
24178
24290
  init_log();
@@ -24189,14 +24301,56 @@ function isProcessAlive(pid) {
24189
24301
  return errnoCode(error62) === "EPERM";
24190
24302
  }
24191
24303
  }
24192
- var import_node_child_process, import_node_util, execFileAsync;
24304
+ var import_node_child_process, import_node_util2, execFileAsync;
24193
24305
  var init_process_identity = __esm({
24194
24306
  "src/platform/process-identity.ts"() {
24195
24307
  "use strict";
24196
24308
  import_node_child_process = require("node:child_process");
24197
- import_node_util = require("node:util");
24309
+ import_node_util2 = require("node:util");
24198
24310
  init_kernel();
24199
- execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
24311
+ execFileAsync = (0, import_node_util2.promisify)(import_node_child_process.execFile);
24312
+ }
24313
+ });
24314
+
24315
+ // src/platform/cgroup-memory.ts
24316
+ function numberOf(text) {
24317
+ const value = Number(text.trim());
24318
+ return text.trim().length > 0 && Number.isFinite(value) && value >= 0 ? value : null;
24319
+ }
24320
+ function parseCgroupMemory(max, current, stat3) {
24321
+ const limitBytes = numberOf(max);
24322
+ const currentBytes = numberOf(current);
24323
+ if (limitBytes === null || limitBytes === 0 || currentBytes === null) return null;
24324
+ const inactiveFile = Number(/^inactive_file (\d+)$/m.exec(stat3)?.[1] ?? 0);
24325
+ return { limitBytes, workingSetBytes: Math.max(0, currentBytes - inactiveFile) };
24326
+ }
24327
+ async function readIn(directory) {
24328
+ const [max, current, stat3] = await Promise.all(
24329
+ ["memory.max", "memory.current", "memory.stat"].map(
24330
+ (name) => (0, import_promises3.readFile)((0, import_node_path2.join)(directory, name), "utf8").catch(() => null)
24331
+ )
24332
+ );
24333
+ if (max === null || max === void 0 || current === null || current === void 0) return null;
24334
+ return parseCgroupMemory(max, current, stat3 ?? "");
24335
+ }
24336
+ async function readCgroupMemory(platform = process.platform, root = CGROUP_ROOT) {
24337
+ if (platform !== "linux") return null;
24338
+ const self = await (0, import_promises3.readFile)("/proc/self/cgroup", "utf8").catch(() => "");
24339
+ const path = /^0::(\/\S*)$/m.exec(self)?.[1];
24340
+ const candidates = path === void 0 || path === "/" ? [root] : [(0, import_node_path2.join)(root, path), root];
24341
+ for (const directory of candidates) {
24342
+ const memory = await readIn(directory);
24343
+ if (memory !== null) return memory;
24344
+ }
24345
+ return null;
24346
+ }
24347
+ var import_promises3, import_node_path2, CGROUP_ROOT;
24348
+ var init_cgroup_memory = __esm({
24349
+ "src/platform/cgroup-memory.ts"() {
24350
+ "use strict";
24351
+ import_promises3 = require("node:fs/promises");
24352
+ import_node_path2 = require("node:path");
24353
+ CGROUP_ROOT = "/sys/fs/cgroup";
24200
24354
  }
24201
24355
  });
24202
24356
 
@@ -24220,15 +24374,27 @@ function parseVmCounters(meminfo, vmstat, loadavg) {
24220
24374
  loadAverage1m: Math.max(0, load)
24221
24375
  };
24222
24376
  }
24377
+ function withCgroupLimit(counters, cgroup) {
24378
+ if (cgroup === null || cgroup.limitBytes >= counters.memTotalBytes) return counters;
24379
+ return {
24380
+ ...counters,
24381
+ memTotalBytes: cgroup.limitBytes,
24382
+ memAvailableBytes: Math.max(
24383
+ 0,
24384
+ Math.min(counters.memAvailableBytes, cgroup.limitBytes - cgroup.workingSetBytes)
24385
+ )
24386
+ };
24387
+ }
24223
24388
  async function readVmCounters(platform = process.platform) {
24224
24389
  if (platform !== "linux") return null;
24225
24390
  try {
24226
24391
  const [meminfo, vmstat, loadavg] = await Promise.all([
24227
- (0, import_promises3.readFile)("/proc/meminfo", "utf8"),
24228
- (0, import_promises3.readFile)("/proc/vmstat", "utf8"),
24229
- (0, import_promises3.readFile)("/proc/loadavg", "utf8")
24392
+ (0, import_promises4.readFile)("/proc/meminfo", "utf8"),
24393
+ (0, import_promises4.readFile)("/proc/vmstat", "utf8"),
24394
+ (0, import_promises4.readFile)("/proc/loadavg", "utf8")
24230
24395
  ]);
24231
- return parseVmCounters(meminfo, vmstat, loadavg);
24396
+ const counters = parseVmCounters(meminfo, vmstat, loadavg);
24397
+ return counters === null ? null : withCgroupLimit(counters, await readCgroupMemory(platform));
24232
24398
  } catch {
24233
24399
  return null;
24234
24400
  }
@@ -24244,10 +24410,10 @@ function parseProcStat(stat3) {
24244
24410
  async function readProcessCpuTable(platform = process.platform) {
24245
24411
  const table = /* @__PURE__ */ new Map();
24246
24412
  if (platform !== "linux") return table;
24247
- const entries = await (0, import_promises3.readdir)("/proc").catch(() => []);
24413
+ const entries = await (0, import_promises4.readdir)("/proc").catch(() => []);
24248
24414
  await Promise.all(
24249
24415
  entries.filter((entry) => /^\d+$/.test(entry)).map(async (entry) => {
24250
- const stat3 = await (0, import_promises3.readFile)(`/proc/${entry}/stat`, "utf8").catch(() => null);
24416
+ const stat3 = await (0, import_promises4.readFile)(`/proc/${entry}/stat`, "utf8").catch(() => null);
24251
24417
  const row = stat3 === null ? null : parseProcStat(stat3);
24252
24418
  if (row !== null) table.set(Number(entry), row);
24253
24419
  })
@@ -24273,11 +24439,12 @@ function processTreeCpuMs(table, pid) {
24273
24439
  }
24274
24440
  return Math.round(total);
24275
24441
  }
24276
- var import_promises3, CLOCK_TICKS_PER_SECOND;
24442
+ var import_promises4, CLOCK_TICKS_PER_SECOND;
24277
24443
  var init_vm_stats = __esm({
24278
24444
  "src/platform/vm-stats.ts"() {
24279
24445
  "use strict";
24280
- import_promises3 = require("node:fs/promises");
24446
+ import_promises4 = require("node:fs/promises");
24447
+ init_cgroup_memory();
24281
24448
  CLOCK_TICKS_PER_SECOND = 100;
24282
24449
  }
24283
24450
  });
@@ -24299,6 +24466,8 @@ var import_node_fs2 = require("node:fs");
24299
24466
 
24300
24467
  // src/api-client/index.ts
24301
24468
  var import_node_crypto = require("node:crypto");
24469
+ var import_node_util = require("node:util");
24470
+ var import_node_zlib = require("node:zlib");
24302
24471
  init_runtime_v2();
24303
24472
  init_kernel();
24304
24473
 
@@ -24458,13 +24627,18 @@ async function send(request, agents) {
24458
24627
  current = next;
24459
24628
  }
24460
24629
  }
24461
- function createHttpTransport() {
24630
+ function withUserAgent(request, userAgent) {
24631
+ if (userAgent === void 0) return request;
24632
+ const named = Object.keys(request.headers).some((name) => name.toLowerCase() === "user-agent");
24633
+ return named ? request : { ...request, headers: { ...request.headers, "user-agent": userAgent } };
24634
+ }
24635
+ function createHttpTransport(options = {}) {
24462
24636
  const agents = {
24463
24637
  http: new import_node_http.Agent({ keepAlive: true, timeout: IDLE_SOCKET_MS }),
24464
24638
  https: new import_node_https.Agent({ keepAlive: true, timeout: IDLE_SOCKET_MS })
24465
24639
  };
24466
24640
  return {
24467
- send: (request) => send(request, agents),
24641
+ send: (request) => send(withUserAgent(request, options.userAgent), agents),
24468
24642
  [Symbol.dispose]: () => {
24469
24643
  agents.http.destroy();
24470
24644
  agents.https.destroy();
@@ -24473,11 +24647,32 @@ function createHttpTransport() {
24473
24647
  }
24474
24648
 
24475
24649
  // src/api-client/index.ts
24650
+ var gzipAsync = (0, import_node_util.promisify)(import_node_zlib.gzip);
24651
+ var GZIP_MIN_BYTES = 1024;
24652
+ async function encodedChunk(bytes) {
24653
+ if (bytes.length < GZIP_MIN_BYTES) return { body: bytes, headers: {} };
24654
+ const compressed = await gzipAsync(bytes, { level: import_node_zlib.constants.Z_BEST_SPEED });
24655
+ return compressed.length < bytes.length ? { body: compressed, headers: { "content-encoding": "gzip" } } : { body: bytes, headers: {} };
24656
+ }
24657
+ async function chunkUpload(headers, bytes) {
24658
+ const encoded = await encodedChunk(bytes);
24659
+ return {
24660
+ method: "POST",
24661
+ headers: {
24662
+ ...headers,
24663
+ ...encoded.headers,
24664
+ "content-type": "application/octet-stream",
24665
+ [RUN_LOG_UPLOAD_HEADERS.sha256]: (0, import_node_crypto.createHash)("sha256").update(bytes).digest("hex")
24666
+ },
24667
+ body: encoded.body
24668
+ };
24669
+ }
24476
24670
  var CENTRAL_SESSION_FEATURES = [
24477
24671
  SESSION_INTERACTION_FEATURE,
24478
24672
  SESSION_OPERATIONS_FEATURE,
24479
24673
  SESSION_SELECTION_FEATURE,
24480
- BOUNDED_DELEGATION_FEATURE
24674
+ BOUNDED_DELEGATION_FEATURE,
24675
+ PROJECT_PATH_FALLBACK_FEATURE
24481
24676
  ];
24482
24677
  var REQUEST_TIMEOUT_MS = 3e4;
24483
24678
  function isRetryableStatus(status) {
@@ -24630,22 +24825,13 @@ function createApiClient({
24630
24825
  receipt: runLogUploadResponseSchema.parse(jsonBody(response)).receipt
24631
24826
  };
24632
24827
  },
24633
- uploadChunk: async (target, offset, bytes, signal) => {
24634
- const response = await request(
24828
+ uploadChunk: async (target, offset, bytes, signal) => toOutcome(
24829
+ await request(
24635
24830
  runLogUploadPath(target.conversationId),
24636
- {
24637
- method: "POST",
24638
- headers: {
24639
- ...uploadHeaders(target, offset),
24640
- "content-type": "application/octet-stream",
24641
- [RUN_LOG_UPLOAD_HEADERS.sha256]: (0, import_node_crypto.createHash)("sha256").update(bytes).digest("hex")
24642
- },
24643
- body: bytes
24644
- },
24831
+ await chunkUpload(uploadHeaders(target, offset), bytes),
24645
24832
  signal
24646
- );
24647
- return toOutcome(response);
24648
- },
24833
+ )
24834
+ ),
24649
24835
  seal: async (target, offset, signal) => {
24650
24836
  const response = await request(
24651
24837
  runLogUploadPath(target.conversationId),
@@ -24670,12 +24856,12 @@ init_kernel();
24670
24856
  init_platform();
24671
24857
 
24672
24858
  // src/cli/commands/activity-lease-producer.ts
24673
- var import_promises4 = require("node:fs/promises");
24674
- var import_node_path4 = require("node:path");
24859
+ var import_promises5 = require("node:fs/promises");
24860
+ var import_node_path5 = require("node:path");
24675
24861
  init_runtime_v2();
24676
24862
 
24677
24863
  // src/holder/activity-file.ts
24678
- var import_node_path2 = require("node:path");
24864
+ var import_node_path3 = require("node:path");
24679
24865
  init_runtime_v2();
24680
24866
  init_zod();
24681
24867
  init_kernel();
@@ -24687,7 +24873,7 @@ var sessionActivitySchema = external_exports.object({
24687
24873
  backgroundTasks: external_exports.number().int().nonnegative()
24688
24874
  });
24689
24875
  function sessionActivityPath(sessionDir) {
24690
- return (0, import_node_path2.join)(sessionDir, ACTIVITY_FILE);
24876
+ return (0, import_node_path3.join)(sessionDir, ACTIVITY_FILE);
24691
24877
  }
24692
24878
  async function readSessionActivity(path) {
24693
24879
  const read = await readJsonFile(path, sessionActivitySchema).catch(() => null);
@@ -24695,7 +24881,7 @@ async function readSessionActivity(path) {
24695
24881
  }
24696
24882
 
24697
24883
  // src/run-log/directory.ts
24698
- var import_node_path3 = require("node:path");
24884
+ var import_node_path4 = require("node:path");
24699
24885
  init_runtime_v2();
24700
24886
  init_zod();
24701
24887
  var runMetaSchema = external_exports.object({
@@ -24718,12 +24904,12 @@ var runMetaSchema = external_exports.object({
24718
24904
  }).optional()
24719
24905
  });
24720
24906
  function runDirectory(runsDir, runId) {
24721
- const dir = (0, import_node_path3.join)(runsDir, runId);
24907
+ const dir = (0, import_node_path4.join)(runsDir, runId);
24722
24908
  return {
24723
24909
  dir,
24724
- log: (0, import_node_path3.join)(dir, "log.jsonl"),
24725
- upload: (0, import_node_path3.join)(dir, "upload.json"),
24726
- meta: (0, import_node_path3.join)(dir, "run.json")
24910
+ log: (0, import_node_path4.join)(dir, "log.jsonl"),
24911
+ upload: (0, import_node_path4.join)(dir, "upload.json"),
24912
+ meta: (0, import_node_path4.join)(dir, "run.json")
24727
24913
  };
24728
24914
  }
24729
24915
 
@@ -24737,22 +24923,72 @@ function delta(current, previous) {
24737
24923
  return previous === void 0 ? 0 : Math.max(0, Math.round(current - previous));
24738
24924
  }
24739
24925
  async function lastOutputAtMs(runsDir, run) {
24740
- const info = await (0, import_promises4.stat)(runDirectory(runsDir, run.runId).log).catch(() => null);
24926
+ const info = await (0, import_promises5.stat)(runDirectory(runsDir, run.runId).log).catch(() => null);
24741
24927
  return info === null ? null : Math.floor(info.mtimeMs);
24742
24928
  }
24743
- async function readHolderActivities(sessionsDir) {
24744
- const names = await (0, import_promises4.readdir)(sessionsDir).catch(() => []);
24929
+ async function readHolderActivities(sessionsDir, cache) {
24930
+ const names = await (0, import_promises5.readdir)(sessionsDir).catch(() => []);
24745
24931
  const found = [];
24932
+ const present = /* @__PURE__ */ new Set();
24746
24933
  for (const name of names) {
24747
24934
  const parsed = conversationIdSchema.safeParse(name);
24748
24935
  if (!parsed.success) continue;
24749
- const activity = await readSessionActivity(sessionActivityPath((0, import_node_path4.join)(sessionsDir, name)));
24936
+ const path = sessionActivityPath((0, import_node_path5.join)(sessionsDir, name));
24937
+ const info = await (0, import_promises5.stat)(path).catch(() => null);
24938
+ if (info === null) continue;
24939
+ present.add(parsed.data);
24940
+ const cached2 = cache.get(parsed.data);
24941
+ const fresh = cached2?.mtimeMs === info.mtimeMs && cached2.size === info.size;
24942
+ const activity = fresh ? cached2.activity : await readSessionActivity(path);
24943
+ if (!fresh) cache.set(parsed.data, { mtimeMs: info.mtimeMs, size: info.size, activity });
24750
24944
  if (activity !== null) found.push({ conversationId: parsed.data, activity });
24751
24945
  }
24946
+ for (const id of cache.keys()) if (!present.has(id)) cache.delete(id);
24752
24947
  return found;
24753
24948
  }
24949
+ function withoutIdleEndedRuns(leased) {
24950
+ return leased.filter((run) => run.state !== "ended" || run.backgroundTasks > 0);
24951
+ }
24952
+ function onlyNewestEndedRun(kept) {
24953
+ const newestEnded = /* @__PURE__ */ new Map();
24954
+ for (const run of kept) {
24955
+ if (run.state !== "ended") continue;
24956
+ const current = newestEnded.get(run.conversationId);
24957
+ if (current === void 0 || (run.lastOutputAtMs ?? 0) > (current.lastOutputAtMs ?? 0)) {
24958
+ newestEnded.set(run.conversationId, run);
24959
+ }
24960
+ }
24961
+ return kept.filter((run) => run.state !== "ended" || newestEnded.get(run.conversationId) === run);
24962
+ }
24963
+ async function leaseRuns(snapshotRuns, activities, runsDir) {
24964
+ const byConversation = new Map(
24965
+ activities.map(({ conversationId, activity }) => [conversationId, activity])
24966
+ );
24967
+ const leased = await Promise.all(
24968
+ snapshotRuns.map(async (run) => {
24969
+ const activity = byConversation.get(run.conversationId);
24970
+ const ownsRun = activity?.runId === run.runId;
24971
+ return {
24972
+ runId: run.runId,
24973
+ conversationId: run.conversationId,
24974
+ state: ownsRun && activity?.awaitingInput === true ? "awaiting_input" : run.state,
24975
+ backgroundTasks: activity?.backgroundTasks ?? 0,
24976
+ lastOutputAtMs: await lastOutputAtMs(runsDir, run)
24977
+ };
24978
+ })
24979
+ );
24980
+ return onlyNewestEndedRun(withoutIdleEndedRuns(leased));
24981
+ }
24754
24982
  function createLeaseProducer(deps) {
24755
- const state = { snapshot: null, sequence: 0, vm: null, cpu: /* @__PURE__ */ new Map(), problem: null, verdict: null };
24983
+ const state = {
24984
+ snapshot: null,
24985
+ sequence: 0,
24986
+ vm: null,
24987
+ cpu: /* @__PURE__ */ new Map(),
24988
+ activities: /* @__PURE__ */ new Map(),
24989
+ problem: null,
24990
+ verdict: null
24991
+ };
24756
24992
  const vmPressure = async () => {
24757
24993
  const current = await deps.readVm();
24758
24994
  if (current === null) return null;
@@ -24769,7 +25005,16 @@ function createLeaseProducer(deps) {
24769
25005
  loadAverage1m: current.loadAverage1m
24770
25006
  };
24771
25007
  };
24772
- const holders = async (activities) => {
25008
+ const holders = async (activities, runOpen) => {
25009
+ if (!runOpen) {
25010
+ return activities.map(
25011
+ ({ conversationId, activity }) => ({
25012
+ conversationId,
25013
+ cliAlive: activity.cliPid !== null && deps.isAlive(activity.cliPid),
25014
+ cpuMsDelta: 0
25015
+ })
25016
+ );
25017
+ }
24773
25018
  const table = activities.some(({ activity }) => activity.cliPid !== null) ? await deps.readCpu() : /* @__PURE__ */ new Map();
24774
25019
  const next = /* @__PURE__ */ new Map();
24775
25020
  const leased = activities.map(({ conversationId, activity }) => {
@@ -24791,45 +25036,16 @@ function createLeaseProducer(deps) {
24791
25036
  if (previous?.pid === pid) return delta(cpuMs, previous.cpuMs);
24792
25037
  return state.sequence === 0 ? 0 : Math.round(cpuMs);
24793
25038
  }
24794
- const runs = async (activities) => {
24795
- const byConversation = new Map(
24796
- activities.map(({ conversationId, activity }) => [conversationId, activity])
24797
- );
24798
- const leased = await Promise.all(
24799
- (state.snapshot?.runs ?? []).map(async (run) => {
24800
- const activity = byConversation.get(run.conversationId);
24801
- const ownsRun = activity?.runId === run.runId;
24802
- return {
24803
- runId: run.runId,
24804
- conversationId: run.conversationId,
24805
- state: ownsRun && activity?.awaitingInput === true ? "awaiting_input" : run.state,
24806
- backgroundTasks: activity?.backgroundTasks ?? 0,
24807
- lastOutputAtMs: await lastOutputAtMs(deps.runsDir, run)
24808
- };
24809
- })
24810
- );
24811
- const kept = leased.filter((run) => run.state !== "ended" || run.backgroundTasks > 0);
24812
- const newestEnded = /* @__PURE__ */ new Map();
24813
- for (const run of kept) {
24814
- if (run.state !== "ended") continue;
24815
- const current = newestEnded.get(run.conversationId);
24816
- if (current === void 0 || (run.lastOutputAtMs ?? 0) > (current.lastOutputAtMs ?? 0)) {
24817
- newestEnded.set(run.conversationId, run);
24818
- }
24819
- }
24820
- return kept.filter(
24821
- (run) => run.state !== "ended" || newestEnded.get(run.conversationId) === run
24822
- );
24823
- };
24824
25039
  const produce = async () => {
24825
- const activities = await readHolderActivities(deps.sessionsDir);
25040
+ const activities = await readHolderActivities(deps.sessionsDir, state.activities);
25041
+ const leasedRuns = await leaseRuns(state.snapshot?.runs ?? [], activities, deps.runsDir);
24826
25042
  const lease = {
24827
25043
  epoch: deps.epoch,
24828
25044
  sequence: state.sequence,
24829
25045
  producedAtMs: Math.floor(deps.clock.now()),
24830
25046
  mainThreadLagMs: Math.max(0, Math.round(deps.mainThreadLagMs())),
24831
- runs: await runs(activities),
24832
- holders: await holders(activities),
25047
+ runs: leasedRuns,
25048
+ holders: await holders(activities, leasedRuns.length > 0),
24833
25049
  vm: await vmPressure(),
24834
25050
  busyRunIds: state.snapshot?.busyRunIds ?? []
24835
25051
  };
@@ -24888,6 +25104,7 @@ var leaseWorkerDataSchema = external_exports.object({
24888
25104
  role: external_exports.literal(ACTIVITY_LEASE_WORKER_ROLE),
24889
25105
  apiUrl: external_exports.url(),
24890
25106
  accessToken: external_exports.string().min(1),
25107
+ userAgent: external_exports.string().min(1),
24891
25108
  epoch: external_exports.number().int().positive(),
24892
25109
  sessionsDir: external_exports.string().min(1),
24893
25110
  runsDir: external_exports.string().min(1),
@@ -24949,6 +25166,7 @@ var WATCHDOG_CHECK_MS = 1e3;
24949
25166
  var WATCHDOG_STALL_MS = 5e3;
24950
25167
  var SIGKILL_AFTER_MS = 5e3;
24951
25168
  var STDERR_FD = 2;
25169
+ var LEASE_COALESCE_MS = 2e3;
24952
25170
  async function endBlockedRuntime(lagMs, thresholdMs, clock, log) {
24953
25171
  log.error("runtime.event_loop_blocked", { lagMs, thresholdMs, exitStatus: WATCHDOG_EXIT_STATUS });
24954
25172
  (0, import_node_fs2.writeSync)(
@@ -24966,7 +25184,7 @@ async function runActivityLeaseWorker(rawData, port) {
24966
25184
  const data = parseLeaseWorkerData(rawData);
24967
25185
  const clock = systemClock;
24968
25186
  const log = __using(_stack, openFileLog(data.logPath, data.logLevel, clock));
24969
- const transport = __using(_stack, createHttpTransport());
25187
+ const transport = __using(_stack, createHttpTransport({ userAgent: data.userAgent }));
24970
25188
  const bearer = { current: data.accessToken };
24971
25189
  const api = createApiClient({
24972
25190
  apiUrl: data.apiUrl,
@@ -25009,6 +25227,13 @@ async function runActivityLeaseWorker(rawData, port) {
25009
25227
  log
25010
25228
  }), true);
25011
25229
  const closed = Promise.withResolvers();
25230
+ const stopping = new AbortController();
25231
+ const sendSoon = createCoalescer(
25232
+ clock,
25233
+ LEASE_COALESCE_MS,
25234
+ () => leases.runNow(),
25235
+ stopping.signal
25236
+ );
25012
25237
  port.on("message", (raw) => {
25013
25238
  const snapshot = parseLeaseSnapshot(raw);
25014
25239
  if (snapshot === null) {
@@ -25016,9 +25241,12 @@ async function runActivityLeaseWorker(rawData, port) {
25016
25241
  return;
25017
25242
  }
25018
25243
  bearer.current = snapshot.accessToken;
25019
- if (producer.update(snapshot)) void leases.runNow();
25244
+ if (producer.update(snapshot)) sendSoon.request();
25245
+ });
25246
+ port.once("close", () => {
25247
+ stopping.abort();
25248
+ closed.resolve();
25020
25249
  });
25021
- port.once("close", () => closed.resolve());
25022
25250
  log.info("activity_lease.worker_started", { epoch: data.epoch, watchdogMs: data.watchdogMs });
25023
25251
  await closed.promise;
25024
25252
  } catch (_) {