@johpaz/hive-agents 0.0.44 → 0.0.45
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/README.md +16 -16
- package/dist/hive.js +2256 -1837
- package/dist/tool-worker.js +30 -0
- package/dist/ui/assets/{AgentCreateForm-DyeTdXUs.js → AgentCreateForm-DzaIT-dA.js} +1 -1
- package/dist/ui/assets/{AgentDetailPage-dmLgf2x5.js → AgentDetailPage-DgqcJceY.js} +1 -1
- package/dist/ui/assets/AgentNewPage-CNSpoOSA.js +1 -0
- package/dist/ui/assets/{AgentsPage-ilEW_WjD.js → AgentsPage-BMUJzTD6.js} +1 -1
- package/dist/ui/assets/{ApiClientPage-CYur6xIG.js → ApiClientPage-Cum_a_3j.js} +1 -1
- package/dist/ui/assets/{CanvasPage-CvMRvq84.js → CanvasPage-o6oCP6uq.js} +1 -1
- package/dist/ui/assets/{ChannelsPage-D4PgfYd2.js → ChannelsPage-WrB0zwLq.js} +1 -1
- package/dist/ui/assets/{DashboardPage-a5UQKJCG.js → DashboardPage-BCd6kNw0.js} +1 -1
- package/dist/ui/assets/{LoginPage-BtMt11D2.js → LoginPage-BTxJdFVG.js} +1 -1
- package/dist/ui/assets/{LogsPage-BeuKjg7-.js → LogsPage-DVV2eHbh.js} +1 -1
- package/dist/ui/assets/{MeetingPage-ClhToyd9.js → MeetingPage-BULIAWzq.js} +1 -1
- package/dist/ui/assets/{ModelSelector-DoMPQbsp.js → ModelSelector-BMYOChYb.js} +1 -1
- package/dist/ui/assets/{ProvidersPage-D6YX7qH4.js → ProvidersPage-BVN5UZrI.js} +1 -1
- package/dist/ui/assets/{RecoverPage-CzouUsK3.js → RecoverPage-7YDQysBL.js} +1 -1
- package/dist/ui/assets/SettingsPage-CYmpFfDn.js +9 -0
- package/dist/ui/assets/{SetupPage-DhyJWZkx.js → SetupPage-Dnmb1Lbv.js} +1 -1
- package/dist/ui/assets/{WebChatPage-DJVJDa6u.js → WebChatPage-DmmdFhIC.js} +1 -1
- package/dist/ui/assets/{alert-CwfjnQnX.js → alert-B9J6KHmt.js} +1 -1
- package/dist/ui/assets/{alert-dialog-BModLupB.js → alert-dialog-KcYQWcJ6.js} +1 -1
- package/dist/ui/assets/{badge-Cn9me8rp.js → badge-88dRb4M8.js} +1 -1
- package/dist/ui/assets/{dialog-BVdxpXxW.js → dialog-Jk4bieO4.js} +1 -1
- package/dist/ui/assets/{es-Ce6Cl5pC.js → es-4I-joeZz.js} +1 -1
- package/dist/ui/assets/{index-CaoDouMU.js → index-Cyw7L0Li.js} +2 -2
- package/dist/ui/assets/{label-CRcJ7SgM.js → label-B_15zZlR.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-mAw1534H.js → useHiveAgentsModelLoad-BnC4jLE-.js} +1 -1
- package/dist/ui/assets/{useProviders-am-lsXGu.js → useProviders-C1xVKLxB.js} +1 -1
- package/dist/ui/index.html +1 -1
- package/package.json +1 -1
- package/packages/core/src/agent/goal-runner.ts +31 -2
- package/packages/core/src/agent/llm-client.ts +22 -1
- package/packages/core/src/agent/proof-packet.ts +59 -0
- package/packages/core/src/agent/run-epoch.ts +33 -0
- package/packages/core/src/agent/run-store.ts +50 -8
- package/packages/core/src/channels/telegram.ts +31 -2
- package/packages/core/src/config/loader.ts +34 -0
- package/packages/core/src/gateway/durable-queue.ts +49 -4
- package/packages/core/src/gateway/job-executors.ts +50 -11
- package/packages/core/src/gateway/job-store.ts +142 -4
- package/packages/core/src/gateway/routes/cron-api.ts +3 -2
- package/packages/core/src/gateway/routes/users.ts +1 -0
- package/packages/core/src/gateway/server.ts +24 -2
- package/packages/core/src/resilience/retry.ts +95 -0
- package/packages/core/src/scheduler/integration.ts +19 -0
- package/packages/core/src/storage/bootstrap.ts +3 -0
- package/packages/core/src/storage/collections.ts +36 -0
- package/packages/core/src/storage/seed.ts +16 -14
- package/packages/skills/src/bundled-data.generated.ts +1107 -1107
- package/dist/ui/assets/AgentNewPage-CgGzBw7_.js +0 -1
- package/dist/ui/assets/SettingsPage-BtXGg87M.js +0 -9
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Bot, GrammyError, InputFile, type Context } from "grammy";
|
|
2
2
|
import { BaseChannel, type ChannelConfig, type IncomingMessage, type OutboundMessage } from "./base.ts";
|
|
3
3
|
import { logger } from "../utils/logger.ts";
|
|
4
|
-
import { updateDoc } from "../storage/hive.ts";
|
|
5
|
-
import type { ChannelDoc } from "../storage/collections.ts";
|
|
4
|
+
import { col, updateDoc } from "../storage/hive.ts";
|
|
5
|
+
import type { ChannelDoc, UserIdentityDoc } from "../storage/collections.ts";
|
|
6
|
+
import { resolveUserId } from "../storage/onboarding";
|
|
6
7
|
|
|
7
8
|
export interface TelegramConfig extends ChannelConfig {
|
|
8
9
|
botToken: string;
|
|
@@ -72,6 +73,29 @@ export class TelegramChannel extends BaseChannel {
|
|
|
72
73
|
});
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Ensures a userIdentities row links this Telegram chat to the single-user
|
|
78
|
+
* account, so cron/task notifications can route to Telegram even when the
|
|
79
|
+
* user's first-ever contact with the bot was a command (e.g. /start) that
|
|
80
|
+
* otherwise replies and returns before reaching the normal
|
|
81
|
+
* handleMessage() → resolveContext() auto-link path.
|
|
82
|
+
*/
|
|
83
|
+
private async linkIdentity(channelUserId: string): Promise<void> {
|
|
84
|
+
try {
|
|
85
|
+
const userId = await resolveUserId({});
|
|
86
|
+
if (!userId) return;
|
|
87
|
+
const identitiesCol = await col<UserIdentityDoc>("userIdentities");
|
|
88
|
+
await identitiesCol.put(`${userId}:telegram`, {
|
|
89
|
+
user_id: userId,
|
|
90
|
+
channel: "telegram",
|
|
91
|
+
channel_user_id: channelUserId,
|
|
92
|
+
linked_at: Date.now(),
|
|
93
|
+
});
|
|
94
|
+
} catch (err) {
|
|
95
|
+
this.log.warn(`Failed to auto-link telegram identity: ${(err as Error).message}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
75
99
|
private async handleTelegramMessage(ctx: Context): Promise<void> {
|
|
76
100
|
const message = ctx.message;
|
|
77
101
|
if (!message) return;
|
|
@@ -101,6 +125,11 @@ export class TelegramChannel extends BaseChannel {
|
|
|
101
125
|
if (now - ts > 60_000) this.recentlyProcessed.delete(id);
|
|
102
126
|
}
|
|
103
127
|
|
|
128
|
+
// Auto-link this chat on first contact, before any command short-circuits.
|
|
129
|
+
if (!isGroup && this.isUserAllowed(chatId)) {
|
|
130
|
+
await this.linkIdentity(chatId);
|
|
131
|
+
}
|
|
132
|
+
|
|
104
133
|
const text = message.text;
|
|
105
134
|
const isCommand = text?.startsWith("/") ?? false;
|
|
106
135
|
|
|
@@ -264,6 +264,25 @@ const RetryConfigSchema = z.object({
|
|
|
264
264
|
maxDelayMs: z.number().optional(),
|
|
265
265
|
});
|
|
266
266
|
|
|
267
|
+
const JobRetryConfigSchema = z.object({
|
|
268
|
+
// Logical-failure retries (executor returned {ok:false}). Separate from
|
|
269
|
+
// JobDoc.attempts, which only counts crash/lease-expiry reclaims.
|
|
270
|
+
maxRetries: z.number().optional(),
|
|
271
|
+
initialDelayMs: z.number().optional(),
|
|
272
|
+
backoffMultiplier: z.number().optional(),
|
|
273
|
+
maxDelayMs: z.number().optional(),
|
|
274
|
+
jitter: z.number().optional(),
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
const HarnessConfigSchema = z.object({
|
|
278
|
+
maxGlobalConcurrency: z.number().optional(),
|
|
279
|
+
taskTimeoutMs: z.number().optional(),
|
|
280
|
+
jobLeaseMs: z.number().optional(),
|
|
281
|
+
runLeaseMs: z.number().optional(),
|
|
282
|
+
leaseRenewMs: z.number().optional(),
|
|
283
|
+
jobRetry: JobRetryConfigSchema.optional(),
|
|
284
|
+
});
|
|
285
|
+
|
|
267
286
|
const HooksConfigSchema = z.object({
|
|
268
287
|
scripts: z.object({
|
|
269
288
|
before_model_resolve: z.string().optional(),
|
|
@@ -367,6 +386,7 @@ const ConfigSchema = z.object({
|
|
|
367
386
|
cron: CronConfigSchema.optional(),
|
|
368
387
|
causalLog: CausalLogConfigSchema.optional(),
|
|
369
388
|
retry: RetryConfigSchema.optional(),
|
|
389
|
+
harness: HarnessConfigSchema.optional(),
|
|
370
390
|
security: SecurityConfigSchema.optional(),
|
|
371
391
|
hooks: HooksConfigSchema.optional(),
|
|
372
392
|
captcha: CaptchaConfigSchema.optional(),
|
|
@@ -516,6 +536,20 @@ function buildDefaultConfig(): Config {
|
|
|
516
536
|
backoffMultiplier: 2,
|
|
517
537
|
maxDelayMs: 30000,
|
|
518
538
|
},
|
|
539
|
+
harness: {
|
|
540
|
+
maxGlobalConcurrency: parseInt(process.env.HIVE_HARNESS_MAX_CONCURRENCY || "4", 10),
|
|
541
|
+
taskTimeoutMs: parseInt(process.env.HIVE_HARNESS_TASK_TIMEOUT_MS || String(30 * 60 * 1000), 10),
|
|
542
|
+
jobLeaseMs: parseInt(process.env.HIVE_HARNESS_JOB_LEASE_MS || String(30 * 60 * 1000), 10),
|
|
543
|
+
runLeaseMs: parseInt(process.env.HIVE_HARNESS_RUN_LEASE_MS || String(2 * 60 * 1000), 10),
|
|
544
|
+
leaseRenewMs: parseInt(process.env.HIVE_HARNESS_LEASE_RENEW_MS || "30000", 10),
|
|
545
|
+
jobRetry: {
|
|
546
|
+
maxRetries: parseInt(process.env.HIVE_HARNESS_JOB_MAX_RETRIES || "3", 10),
|
|
547
|
+
initialDelayMs: parseInt(process.env.HIVE_HARNESS_JOB_RETRY_INITIAL_MS || "1000", 10),
|
|
548
|
+
backoffMultiplier: parseFloat(process.env.HIVE_HARNESS_JOB_RETRY_MULTIPLIER || "2"),
|
|
549
|
+
maxDelayMs: parseInt(process.env.HIVE_HARNESS_JOB_RETRY_MAX_MS || String(5 * 60 * 1000), 10),
|
|
550
|
+
jitter: parseFloat(process.env.HIVE_HARNESS_JOB_RETRY_JITTER || "0.2"),
|
|
551
|
+
},
|
|
552
|
+
},
|
|
519
553
|
security: {
|
|
520
554
|
maxMessageLength: {
|
|
521
555
|
telegram: 4096,
|
|
@@ -20,12 +20,16 @@ import {
|
|
|
20
20
|
claimJob,
|
|
21
21
|
completeJob,
|
|
22
22
|
failJob,
|
|
23
|
+
failJobOrRetry,
|
|
23
24
|
cancelJob,
|
|
24
25
|
reclaimOrInterrupt,
|
|
25
26
|
findPendingJobsByLane,
|
|
26
27
|
findAllPendingJobs,
|
|
27
28
|
findExpiredLeases,
|
|
28
29
|
getJob,
|
|
30
|
+
loadJobRetryPolicy,
|
|
31
|
+
DEFAULT_JOB_RETRY_POLICY,
|
|
32
|
+
type JobRetryPolicy,
|
|
29
33
|
} from "./job-store";
|
|
30
34
|
import type { JobDoc } from "../storage/collections";
|
|
31
35
|
import { getBootId } from "../storage/boot-id";
|
|
@@ -46,6 +50,10 @@ export interface JobExecutorResult {
|
|
|
46
50
|
ok: boolean;
|
|
47
51
|
result?: unknown;
|
|
48
52
|
error?: string;
|
|
53
|
+
/** Logical failures default to retryable; set false for terminal errors (validation, not-found) that a retry can't fix. Ignored when ok=true. */
|
|
54
|
+
retryable?: boolean;
|
|
55
|
+
/** Stable failure code for observability/tooling, e.g. {code:"PROVIDER_TIMEOUT"}. */
|
|
56
|
+
failureSignature?: string;
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
export interface JobLiveCallbacks {
|
|
@@ -71,6 +79,7 @@ export function registerExecutor(type: JobType, executor: JobExecutor): void {
|
|
|
71
79
|
export class DurableLaneQueue {
|
|
72
80
|
private maxGlobalConcurrency: number;
|
|
73
81
|
private taskTimeoutMs: number;
|
|
82
|
+
private jobRetryPolicy: JobRetryPolicy;
|
|
74
83
|
private runningCount = 0;
|
|
75
84
|
private runningAborts = new Map<string, { lane: string; controller: AbortController }>();
|
|
76
85
|
private dispatchTimers = new Map<string, ReturnType<typeof setInterval>>();
|
|
@@ -80,9 +89,11 @@ export class DurableLaneQueue {
|
|
|
80
89
|
constructor(options: {
|
|
81
90
|
maxGlobalConcurrency?: number;
|
|
82
91
|
taskTimeoutMs?: number;
|
|
92
|
+
jobRetryPolicy?: JobRetryPolicy;
|
|
83
93
|
} = {}) {
|
|
84
94
|
this.maxGlobalConcurrency = options.maxGlobalConcurrency ?? DEFAULT_MAX_GLOBAL_CONCURRENCY;
|
|
85
95
|
this.taskTimeoutMs = options.taskTimeoutMs ?? DEFAULT_TASK_TIMEOUT_MS;
|
|
96
|
+
this.jobRetryPolicy = options.jobRetryPolicy ?? DEFAULT_JOB_RETRY_POLICY;
|
|
86
97
|
this.bootId = getBootId();
|
|
87
98
|
}
|
|
88
99
|
|
|
@@ -99,6 +110,8 @@ export class DurableLaneQueue {
|
|
|
99
110
|
priority?: number;
|
|
100
111
|
max_attempts?: number;
|
|
101
112
|
not_before?: number;
|
|
113
|
+
/** Client-supplied dedup key: a repeated key returns the existing job instead of creating a new one. */
|
|
114
|
+
idempotency_key?: string | null;
|
|
102
115
|
callbacks?: JobLiveCallbacks;
|
|
103
116
|
}): Promise<JobDoc> {
|
|
104
117
|
const job = await createJob({
|
|
@@ -109,6 +122,7 @@ export class DurableLaneQueue {
|
|
|
109
122
|
priority: input.priority,
|
|
110
123
|
max_attempts: input.max_attempts,
|
|
111
124
|
not_before: input.not_before,
|
|
125
|
+
idempotency_key: input.idempotency_key,
|
|
112
126
|
});
|
|
113
127
|
|
|
114
128
|
// Stash live callbacks in memory (not serializable)
|
|
@@ -154,8 +168,8 @@ export class DurableLaneQueue {
|
|
|
154
168
|
*/
|
|
155
169
|
start(): void {
|
|
156
170
|
if (this.leaseCheckTimer) return;
|
|
157
|
-
this.leaseCheckTimer = setInterval(() => this.
|
|
158
|
-
log.info(`[start]
|
|
171
|
+
this.leaseCheckTimer = setInterval(() => this.runMaintenanceTick(), LEASE_CHECK_INTERVAL_MS);
|
|
172
|
+
log.info(`[start] Maintenance tick running every ${LEASE_CHECK_INTERVAL_MS}ms`);
|
|
159
173
|
// Without this, jobs reclaimed to "pending" by reconcileOnBoot (or enqueued
|
|
160
174
|
// right before a crash) would sit until a new enqueue touched their lane.
|
|
161
175
|
this.dispatchPendingLanes().catch((err) => {
|
|
@@ -163,6 +177,20 @@ export class DurableLaneQueue {
|
|
|
163
177
|
});
|
|
164
178
|
}
|
|
165
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Periodic tick: reclaim crashed jobs (expired leases) AND re-dispatch
|
|
182
|
+
* lanes with jobs whose `not_before` (e.g. a backoff delay from
|
|
183
|
+
* `failJobOrRetry`) has now elapsed. `dispatchPendingLanes` is safe to call
|
|
184
|
+
* repeatedly — `scheduleDispatch` debounces per lane and a lane with
|
|
185
|
+
* nothing due is a cheap no-op.
|
|
186
|
+
*/
|
|
187
|
+
private async runMaintenanceTick(): Promise<void> {
|
|
188
|
+
await this.checkExpiredLeases();
|
|
189
|
+
await this.dispatchPendingLanes().catch((err) => {
|
|
190
|
+
log.error(`[runMaintenanceTick] Failed to dispatch pending lanes: ${(err as Error).message}`);
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
166
194
|
private async dispatchPendingLanes(): Promise<void> {
|
|
167
195
|
const pending = await findAllPendingJobs();
|
|
168
196
|
const lanes = new Set(pending.map((j) => j.lane));
|
|
@@ -253,13 +281,25 @@ export class DurableLaneQueue {
|
|
|
253
281
|
if (result.ok) {
|
|
254
282
|
await completeJob(job.id, result.result ?? null, this.bootId);
|
|
255
283
|
} else {
|
|
256
|
-
|
|
284
|
+
const error = result.error ?? "Unknown error";
|
|
285
|
+
// chat_turn is user-facing — never auto-retry a logical failure, the
|
|
286
|
+
// user just sees the error and can re-ask.
|
|
287
|
+
if (job.type !== "chat_turn" && result.retryable !== false) {
|
|
288
|
+
await failJobOrRetry(job.id, error, this.bootId, this.jobRetryPolicy);
|
|
289
|
+
} else {
|
|
290
|
+
await failJob(job.id, error, this.bootId);
|
|
291
|
+
}
|
|
257
292
|
}
|
|
258
293
|
} catch (err) {
|
|
259
294
|
if ((err as Error).name === "AbortError") {
|
|
260
295
|
await cancelJob(job.id);
|
|
261
296
|
} else {
|
|
262
|
-
|
|
297
|
+
const error = (err as Error).message;
|
|
298
|
+
if (job.type !== "chat_turn") {
|
|
299
|
+
await failJobOrRetry(job.id, error, this.bootId, this.jobRetryPolicy);
|
|
300
|
+
} else {
|
|
301
|
+
await failJob(job.id, error, this.bootId);
|
|
302
|
+
}
|
|
263
303
|
}
|
|
264
304
|
} finally {
|
|
265
305
|
clearTimeout(timeoutId);
|
|
@@ -296,6 +336,10 @@ export class DurableLaneQueue {
|
|
|
296
336
|
getMaxGlobalConcurrency(): number {
|
|
297
337
|
return this.maxGlobalConcurrency;
|
|
298
338
|
}
|
|
339
|
+
|
|
340
|
+
getJobRetryPolicy(): JobRetryPolicy {
|
|
341
|
+
return this.jobRetryPolicy;
|
|
342
|
+
}
|
|
299
343
|
}
|
|
300
344
|
|
|
301
345
|
// Live callback stash — not serializable, kept in memory only
|
|
@@ -314,6 +358,7 @@ export function getDurableQueue(): DurableLaneQueue {
|
|
|
314
358
|
export function initDurableQueue(options?: {
|
|
315
359
|
maxGlobalConcurrency?: number;
|
|
316
360
|
taskTimeoutMs?: number;
|
|
361
|
+
jobRetryPolicy?: JobRetryPolicy;
|
|
317
362
|
}): DurableLaneQueue {
|
|
318
363
|
_durableQueue = new DurableLaneQueue(options);
|
|
319
364
|
_durableQueue.start();
|
|
@@ -14,12 +14,14 @@
|
|
|
14
14
|
import { registerExecutor, type JobExecutor } from "./durable-queue";
|
|
15
15
|
import { logger } from "../utils/logger";
|
|
16
16
|
import { col, updateDoc } from "../storage/hive";
|
|
17
|
+
import { isRetryableError } from "../resilience/retry";
|
|
17
18
|
import type { JobDoc, TaskDoc, AgentRunDoc } from "../storage/collections";
|
|
18
19
|
import { runAgent, runAgentIsolated } from "../agent/agent-loop";
|
|
19
|
-
import { createRun, completeRun, failRun, interruptRun, getRun, reclaimRun, bumpTurn, startLeaseRenewal, stopLeaseRenewal } from "../agent/run-store";
|
|
20
|
+
import { createRun, completeRun, failRun, interruptRun, getRun, reclaimRun, bumpTurn, startLeaseRenewal, stopLeaseRenewal, deserializeAcceptance, deserializeEpoch } from "../agent/run-store";
|
|
20
21
|
import { getDurableQueue } from "./durable-queue";
|
|
21
22
|
import { sendToUserChannel } from "./channel-notify";
|
|
22
23
|
import { verifyGoal } from "../agent/goal-runner";
|
|
24
|
+
import { buildProofPacket } from "../agent/proof-packet";
|
|
23
25
|
import { runWebchatTurn, type WebchatTurnPayload } from "./webchat-turn";
|
|
24
26
|
import { agentBus } from "../events/agent-bus";
|
|
25
27
|
import { resolveContext } from "./resolver";
|
|
@@ -69,8 +71,8 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
|
|
|
69
71
|
|
|
70
72
|
const agentsCol = await col<{ id: string; name: string; enabled: boolean }>("agents");
|
|
71
73
|
const workerEntry = await agentsCol.get(workerId);
|
|
72
|
-
if (!workerEntry) return { ok: false, error: `Worker not found: ${workerId}
|
|
73
|
-
if (!workerEntry.doc.enabled) return { ok: false, error: `Worker disabled: ${workerEntry.doc.name}
|
|
74
|
+
if (!workerEntry) return { ok: false, error: `Worker not found: ${workerId}`, retryable: false };
|
|
75
|
+
if (!workerEntry.doc.enabled) return { ok: false, error: `Worker disabled: ${workerEntry.doc.name}`, retryable: false };
|
|
74
76
|
|
|
75
77
|
const workerName = workerEntry.doc.name;
|
|
76
78
|
agentBus.notifyTaskStarted(workerId, workerName, 0, taskName, "");
|
|
@@ -111,7 +113,7 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
|
|
|
111
113
|
updated_at: Date.now(),
|
|
112
114
|
} as Partial<TaskDoc>).catch(() => {});
|
|
113
115
|
}
|
|
114
|
-
return { ok: false, error: "Aborted" };
|
|
116
|
+
return { ok: false, error: "Aborted", retryable: false };
|
|
115
117
|
}
|
|
116
118
|
|
|
117
119
|
agentBus.notifyTaskCompleted(workerId, workerName, 0, taskName, "", result);
|
|
@@ -141,7 +143,7 @@ const workerTaskExecutor: JobExecutor = async (job, signal) => {
|
|
|
141
143
|
} as Partial<TaskDoc>).catch(() => {});
|
|
142
144
|
}
|
|
143
145
|
|
|
144
|
-
return { ok: false, error: errorMsg };
|
|
146
|
+
return { ok: false, error: errorMsg, retryable: isRetryableError(err) };
|
|
145
147
|
}
|
|
146
148
|
};
|
|
147
149
|
|
|
@@ -187,7 +189,7 @@ const projectTaskExecutor: JobExecutor = async (job, signal) => {
|
|
|
187
189
|
status: "pending",
|
|
188
190
|
updated_at: Date.now(),
|
|
189
191
|
} as Partial<TaskDoc>).catch(() => {});
|
|
190
|
-
return { ok: false, error: "Aborted" };
|
|
192
|
+
return { ok: false, error: "Aborted", retryable: false };
|
|
191
193
|
}
|
|
192
194
|
|
|
193
195
|
// Update TaskDoc → completed
|
|
@@ -199,6 +201,19 @@ const projectTaskExecutor: JobExecutor = async (job, signal) => {
|
|
|
199
201
|
updated_at: Date.now(),
|
|
200
202
|
} as Partial<TaskDoc>).catch(() => {});
|
|
201
203
|
|
|
204
|
+
if (runId) {
|
|
205
|
+
const finishedRun = await getRun(runId);
|
|
206
|
+
await buildProofPacket({
|
|
207
|
+
runId,
|
|
208
|
+
agentId: workerId,
|
|
209
|
+
intendedOutcome: taskDescription,
|
|
210
|
+
met: true,
|
|
211
|
+
checksRun: [],
|
|
212
|
+
evidence: [typeof result === "string" ? result : JSON.stringify(result)].filter(Boolean),
|
|
213
|
+
epoch: finishedRun ? deserializeEpoch(finishedRun) : null,
|
|
214
|
+
}).catch(() => {});
|
|
215
|
+
}
|
|
216
|
+
|
|
202
217
|
// Kick the TaskDriver to check for newly-ready tasks
|
|
203
218
|
try {
|
|
204
219
|
const { getTaskDriver } = await import("../scheduler/task-driver");
|
|
@@ -220,7 +235,7 @@ const projectTaskExecutor: JobExecutor = async (job, signal) => {
|
|
|
220
235
|
await getTaskDriver().kick("project_task:failed");
|
|
221
236
|
} catch { /* non-critical */ }
|
|
222
237
|
|
|
223
|
-
return { ok: false, error: errorMsg };
|
|
238
|
+
return { ok: false, error: errorMsg, retryable: isRetryableError(err) };
|
|
224
239
|
}
|
|
225
240
|
};
|
|
226
241
|
|
|
@@ -258,6 +273,9 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
258
273
|
}
|
|
259
274
|
};
|
|
260
275
|
|
|
276
|
+
const acceptance = deserializeAcceptance(goalRun);
|
|
277
|
+
const epoch = deserializeEpoch(goalRun);
|
|
278
|
+
|
|
261
279
|
await reclaimRun(goalRunId).catch(() => {});
|
|
262
280
|
startLeaseRenewal(goalRunId);
|
|
263
281
|
|
|
@@ -269,7 +287,7 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
269
287
|
for (;;) {
|
|
270
288
|
if (signal.aborted) {
|
|
271
289
|
await interruptRun(goalRunId, "Goal run aborted").catch(() => {});
|
|
272
|
-
return { ok: false, error: "Aborted" };
|
|
290
|
+
return { ok: false, error: "Aborted", retryable: false };
|
|
273
291
|
}
|
|
274
292
|
|
|
275
293
|
// HARD budget check against the accumulated goal run row
|
|
@@ -280,7 +298,17 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
280
298
|
const summary = `intentos ${attempts}/${maxAttempts}, turnos ${turnsUsed}/${maxTurns}, tokens ${tokensUsed}/${maxTokens}`;
|
|
281
299
|
await failRun(goalRunId, `Goal not met — budget exhausted (${summary}). ${lastReason}`.trim());
|
|
282
300
|
await notify(`❌ Meta no cumplida: "${goal}". Presupuesto agotado (${summary}).${lastReason ? ` Última razón: ${lastReason}` : ""}`);
|
|
283
|
-
|
|
301
|
+
await buildProofPacket({
|
|
302
|
+
runId: goalRunId,
|
|
303
|
+
agentId,
|
|
304
|
+
intendedOutcome: goal,
|
|
305
|
+
met: false,
|
|
306
|
+
checksRun: acceptance ? acceptance.map((a) => a.checkTool ?? "llm_verifier") : [checkTool ?? "llm_verifier"],
|
|
307
|
+
evidence: [lastReason || "budget exhausted before verification succeeded"],
|
|
308
|
+
knownLimits: `Budget exhausted: ${summary}`,
|
|
309
|
+
epoch,
|
|
310
|
+
}).catch(() => {});
|
|
311
|
+
return { ok: false, error: `Goal budget exhausted (${summary})`, retryable: false };
|
|
284
312
|
}
|
|
285
313
|
|
|
286
314
|
const turnMessage = attempts === 0
|
|
@@ -313,16 +341,27 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
313
341
|
} as Partial<AgentRunDoc>).catch(() => {});
|
|
314
342
|
|
|
315
343
|
// Verify: deterministic tool when configured, LLM verifier otherwise
|
|
344
|
+
// (or one check per acceptance criterion when the run has them)
|
|
316
345
|
const providerCfg = await resolveGoalProviderCfg(agentId);
|
|
317
346
|
const verdict = await verifyGoal(goal, checkTool, [
|
|
318
347
|
{ role: "user", content: `Meta: ${goal}` },
|
|
319
348
|
{ role: "assistant", content: turnContent || "(sin respuesta)" },
|
|
320
|
-
], providerCfg);
|
|
349
|
+
], providerCfg, acceptance);
|
|
321
350
|
|
|
322
351
|
if (verdict.met) {
|
|
323
352
|
await completeRun(goalRunId, lastContent);
|
|
324
353
|
await notify(`✅ Meta cumplida: "${goal}". ${verdict.reason}`);
|
|
325
354
|
log.info(`[goal_run] Goal met after ${attempts} attempt(s): ${verdict.reason}`);
|
|
355
|
+
await buildProofPacket({
|
|
356
|
+
runId: goalRunId,
|
|
357
|
+
agentId,
|
|
358
|
+
intendedOutcome: goal,
|
|
359
|
+
met: true,
|
|
360
|
+
acceptanceResults: verdict.acceptanceResults,
|
|
361
|
+
checksRun: acceptance ? acceptance.map((a) => a.checkTool ?? "llm_verifier") : [checkTool ?? "llm_verifier"],
|
|
362
|
+
evidence: [verdict.reason, lastContent].filter(Boolean),
|
|
363
|
+
epoch,
|
|
364
|
+
}).catch(() => {});
|
|
326
365
|
return { ok: true, result: { met: true, attempts, reason: verdict.reason, content: lastContent } };
|
|
327
366
|
}
|
|
328
367
|
|
|
@@ -331,7 +370,7 @@ const goalRunExecutor: JobExecutor = async (job, signal) => {
|
|
|
331
370
|
}
|
|
332
371
|
} catch (err) {
|
|
333
372
|
await failRun(goalRunId, (err as Error).message).catch(() => {});
|
|
334
|
-
return { ok: false, error: (err as Error).message };
|
|
373
|
+
return { ok: false, error: (err as Error).message, retryable: isRetryableError(err) };
|
|
335
374
|
} finally {
|
|
336
375
|
stopLeaseRenewal(goalRunId);
|
|
337
376
|
}
|
|
@@ -5,16 +5,66 @@
|
|
|
5
5
|
* path guarantees only one process wins the race for the same job.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { col, nextId, updateDoc } from "../storage/hive";
|
|
8
|
+
import { col, nextId, updateDoc, toIndexable } from "../storage/hive";
|
|
9
9
|
import type { JobDoc } from "../storage/collections";
|
|
10
10
|
import { getBootId } from "../storage/boot-id";
|
|
11
11
|
import { logger } from "../utils/logger";
|
|
12
|
+
import { loadConfig } from "../config/loader";
|
|
12
13
|
|
|
13
14
|
const log = logger.child("job-store");
|
|
14
15
|
|
|
15
|
-
const LEASE_DURATION_MS = 30 * 60 * 1000;
|
|
16
16
|
const MAX_RETRIES = 5;
|
|
17
17
|
|
|
18
|
+
function jobLeaseDurationMs(): number {
|
|
19
|
+
return loadConfig().harness?.jobLeaseMs ?? 30 * 60 * 1000;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface JobRetryPolicy {
|
|
23
|
+
maxRetries: number;
|
|
24
|
+
initialDelayMs: number;
|
|
25
|
+
backoffMultiplier: number;
|
|
26
|
+
maxDelayMs: number;
|
|
27
|
+
jitter: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const DEFAULT_JOB_RETRY_POLICY: JobRetryPolicy = {
|
|
31
|
+
maxRetries: 3,
|
|
32
|
+
initialDelayMs: 1000,
|
|
33
|
+
backoffMultiplier: 2,
|
|
34
|
+
maxDelayMs: 5 * 60 * 1000,
|
|
35
|
+
jitter: 0.2,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export function loadJobRetryPolicy(): JobRetryPolicy {
|
|
39
|
+
const cfg = loadConfig().harness?.jobRetry;
|
|
40
|
+
return {
|
|
41
|
+
maxRetries: cfg?.maxRetries ?? DEFAULT_JOB_RETRY_POLICY.maxRetries,
|
|
42
|
+
initialDelayMs: cfg?.initialDelayMs ?? DEFAULT_JOB_RETRY_POLICY.initialDelayMs,
|
|
43
|
+
backoffMultiplier: cfg?.backoffMultiplier ?? DEFAULT_JOB_RETRY_POLICY.backoffMultiplier,
|
|
44
|
+
maxDelayMs: cfg?.maxDelayMs ?? DEFAULT_JOB_RETRY_POLICY.maxDelayMs,
|
|
45
|
+
jitter: cfg?.jitter ?? DEFAULT_JOB_RETRY_POLICY.jitter,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Exponential backoff with full jitter, capped at policy.maxDelayMs. */
|
|
50
|
+
export function computeBackoffDelay(retryCount: number, policy: JobRetryPolicy): number {
|
|
51
|
+
const base = Math.min(policy.maxDelayMs, policy.initialDelayMs * Math.pow(policy.backoffMultiplier, retryCount));
|
|
52
|
+
const jitterAmount = base * policy.jitter * Math.random();
|
|
53
|
+
return Math.round(base + jitterAmount);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Small randomized delay between OCC-conflict retries to reduce thundering-herd contention. */
|
|
57
|
+
function occRetryDelay(attempt: number): Promise<void> {
|
|
58
|
+
const ms = 5 * (attempt + 1) + Math.random() * 10;
|
|
59
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function findByIdempotencyKey(key: string): Promise<JobDoc | null> {
|
|
63
|
+
const c = await col<JobDoc>("jobQueue");
|
|
64
|
+
const entries = await c.findBy("idempotency_key", key);
|
|
65
|
+
return entries.length > 0 ? entries[0].doc : null;
|
|
66
|
+
}
|
|
67
|
+
|
|
18
68
|
export async function createJob(input: {
|
|
19
69
|
lane: string;
|
|
20
70
|
type: JobDoc["type"];
|
|
@@ -23,7 +73,17 @@ export async function createJob(input: {
|
|
|
23
73
|
priority?: number;
|
|
24
74
|
max_attempts?: number;
|
|
25
75
|
not_before?: number;
|
|
76
|
+
/** Client-supplied dedup key: a repeated key returns the existing job instead of creating a new one. */
|
|
77
|
+
idempotency_key?: string | null;
|
|
26
78
|
}): Promise<JobDoc> {
|
|
79
|
+
if (input.idempotency_key) {
|
|
80
|
+
const existing = await findByIdempotencyKey(input.idempotency_key);
|
|
81
|
+
if (existing) {
|
|
82
|
+
log.info(`[createJob] Idempotent hit for key=${input.idempotency_key} → job ${existing.id}`);
|
|
83
|
+
return existing;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
27
87
|
const id = await nextId("jobQueue");
|
|
28
88
|
const now = Date.now();
|
|
29
89
|
const doc: JobDoc = {
|
|
@@ -44,6 +104,9 @@ export async function createJob(input: {
|
|
|
44
104
|
created_at: now,
|
|
45
105
|
started_at: null,
|
|
46
106
|
finished_at: null,
|
|
107
|
+
retry_count: 0,
|
|
108
|
+
last_error: null,
|
|
109
|
+
idempotency_key: toIndexable(input.idempotency_key ?? null),
|
|
47
110
|
};
|
|
48
111
|
const c = await col<JobDoc>("jobQueue");
|
|
49
112
|
await c.put(id, doc, { expectedVersion: 0 });
|
|
@@ -71,7 +134,7 @@ export async function claimJob(jobId: string, bootId: string = getBootId()): Pro
|
|
|
71
134
|
status: "running",
|
|
72
135
|
attempts: doc.attempts + 1,
|
|
73
136
|
boot_id: bootId,
|
|
74
|
-
lease_expires_at: now +
|
|
137
|
+
lease_expires_at: now + jobLeaseDurationMs(),
|
|
75
138
|
started_at: doc.started_at ?? now,
|
|
76
139
|
};
|
|
77
140
|
try {
|
|
@@ -80,6 +143,7 @@ export async function claimJob(jobId: string, bootId: string = getBootId()): Pro
|
|
|
80
143
|
return updated;
|
|
81
144
|
} catch {
|
|
82
145
|
// OCC conflict — retry
|
|
146
|
+
await occRetryDelay(attempt);
|
|
83
147
|
}
|
|
84
148
|
}
|
|
85
149
|
log.warn(`[claimJob] Too much contention on job ${jobId}`);
|
|
@@ -101,13 +165,14 @@ export async function renewLease(jobId: string, bootId: string = getBootId()): P
|
|
|
101
165
|
|
|
102
166
|
const updated: JobDoc = {
|
|
103
167
|
...doc,
|
|
104
|
-
lease_expires_at: Date.now() +
|
|
168
|
+
lease_expires_at: Date.now() + jobLeaseDurationMs(),
|
|
105
169
|
};
|
|
106
170
|
try {
|
|
107
171
|
await c.put(jobId, updated, { expectedVersion: entry.version });
|
|
108
172
|
return true;
|
|
109
173
|
} catch {
|
|
110
174
|
// OCC conflict — retry
|
|
175
|
+
await occRetryDelay(attempt);
|
|
111
176
|
}
|
|
112
177
|
}
|
|
113
178
|
log.warn(`[renewLease] Too much contention on job ${jobId}`);
|
|
@@ -138,6 +203,7 @@ export async function completeJob(jobId: string, result: unknown, bootId: string
|
|
|
138
203
|
return;
|
|
139
204
|
} catch {
|
|
140
205
|
// OCC conflict — retry
|
|
206
|
+
await occRetryDelay(attempt);
|
|
141
207
|
}
|
|
142
208
|
}
|
|
143
209
|
log.warn(`[completeJob] Too much contention on job ${jobId}`);
|
|
@@ -156,6 +222,7 @@ export async function failJob(jobId: string, error: string, bootId: string = get
|
|
|
156
222
|
...doc,
|
|
157
223
|
status: "failed",
|
|
158
224
|
error,
|
|
225
|
+
last_error: error,
|
|
159
226
|
finished_at: Date.now(),
|
|
160
227
|
boot_id: null,
|
|
161
228
|
lease_expires_at: null,
|
|
@@ -166,11 +233,79 @@ export async function failJob(jobId: string, error: string, bootId: string = get
|
|
|
166
233
|
return;
|
|
167
234
|
} catch {
|
|
168
235
|
// OCC conflict — retry
|
|
236
|
+
await occRetryDelay(attempt);
|
|
169
237
|
}
|
|
170
238
|
}
|
|
171
239
|
log.warn(`[failJob] Too much contention on job ${jobId}`);
|
|
172
240
|
}
|
|
173
241
|
|
|
242
|
+
/**
|
|
243
|
+
* Fail a job that returned a LOGICAL failure ({ok:false}), retrying with
|
|
244
|
+
* exponential backoff + jitter up to `policy.maxRetries` before giving up.
|
|
245
|
+
* Distinct from `attempts`/`reclaimOrInterrupt`, which only handle crash /
|
|
246
|
+
* lease-expiry recovery. `chat_turn` jobs must never be routed here (caller's
|
|
247
|
+
* responsibility) — a user-facing turn should not silently retry later.
|
|
248
|
+
*/
|
|
249
|
+
export async function failJobOrRetry(
|
|
250
|
+
jobId: string,
|
|
251
|
+
error: string,
|
|
252
|
+
bootId: string = getBootId(),
|
|
253
|
+
policy: JobRetryPolicy = DEFAULT_JOB_RETRY_POLICY
|
|
254
|
+
): Promise<JobDoc | null> {
|
|
255
|
+
const c = await col<JobDoc>("jobQueue");
|
|
256
|
+
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
|
257
|
+
const entry = await c.get(jobId);
|
|
258
|
+
if (!entry) return null;
|
|
259
|
+
const doc = entry.doc;
|
|
260
|
+
if (doc.status !== "running") return null;
|
|
261
|
+
if (doc.boot_id !== bootId) return null;
|
|
262
|
+
|
|
263
|
+
const now = Date.now();
|
|
264
|
+
const retryCount = doc.retry_count ?? 0;
|
|
265
|
+
|
|
266
|
+
if (retryCount >= policy.maxRetries) {
|
|
267
|
+
const updated: JobDoc = {
|
|
268
|
+
...doc,
|
|
269
|
+
status: "failed",
|
|
270
|
+
error,
|
|
271
|
+
last_error: error,
|
|
272
|
+
finished_at: now,
|
|
273
|
+
boot_id: null,
|
|
274
|
+
lease_expires_at: null,
|
|
275
|
+
};
|
|
276
|
+
try {
|
|
277
|
+
await c.put(jobId, updated, { expectedVersion: entry.version });
|
|
278
|
+
log.info(`[failJobOrRetry] Job ${jobId} failed terminally after ${retryCount} retr${retryCount === 1 ? "y" : "ies"}: ${error}`);
|
|
279
|
+
return updated;
|
|
280
|
+
} catch {
|
|
281
|
+
await occRetryDelay(attempt);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const delay = computeBackoffDelay(retryCount, policy);
|
|
287
|
+
const updated: JobDoc = {
|
|
288
|
+
...doc,
|
|
289
|
+
status: "pending",
|
|
290
|
+
retry_count: retryCount + 1,
|
|
291
|
+
last_error: error,
|
|
292
|
+
not_before: now + delay,
|
|
293
|
+
boot_id: null,
|
|
294
|
+
lease_expires_at: null,
|
|
295
|
+
};
|
|
296
|
+
try {
|
|
297
|
+
await c.put(jobId, updated, { expectedVersion: entry.version });
|
|
298
|
+
log.info(`[failJobOrRetry] Job ${jobId} scheduled for retry ${retryCount + 1}/${policy.maxRetries} in ${delay}ms: ${error}`);
|
|
299
|
+
return updated;
|
|
300
|
+
} catch {
|
|
301
|
+
// OCC conflict — retry
|
|
302
|
+
await occRetryDelay(attempt);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
log.warn(`[failJobOrRetry] Too much contention on job ${jobId}`);
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
|
|
174
309
|
/**
|
|
175
310
|
* Re-enqueue a job whose lease has expired back to pending, bumping its
|
|
176
311
|
* attempt count (already bumped at claim time). If attempts >= max_attempts,
|
|
@@ -204,6 +339,7 @@ export async function reclaimOrInterrupt(jobId: string, opts?: { force?: boolean
|
|
|
204
339
|
log.warn(`[reclaimOrInterrupt] Job ${jobId} interrupted (attempts exhausted)`);
|
|
205
340
|
return updated;
|
|
206
341
|
} catch {
|
|
342
|
+
await occRetryDelay(attempt);
|
|
207
343
|
continue;
|
|
208
344
|
}
|
|
209
345
|
}
|
|
@@ -220,6 +356,7 @@ export async function reclaimOrInterrupt(jobId: string, opts?: { force?: boolean
|
|
|
220
356
|
return updated;
|
|
221
357
|
} catch {
|
|
222
358
|
// OCC conflict — retry
|
|
359
|
+
await occRetryDelay(attempt);
|
|
223
360
|
}
|
|
224
361
|
}
|
|
225
362
|
log.warn(`[reclaimOrInterrupt] Too much contention on job ${jobId}`);
|
|
@@ -247,6 +384,7 @@ export async function cancelJob(jobId: string): Promise<boolean> {
|
|
|
247
384
|
return true;
|
|
248
385
|
} catch {
|
|
249
386
|
// OCC conflict — retry
|
|
387
|
+
await occRetryDelay(attempt);
|
|
250
388
|
}
|
|
251
389
|
}
|
|
252
390
|
return false;
|
|
@@ -485,6 +485,7 @@ export async function handleGetCronChannels(
|
|
|
485
485
|
const usersCol = await col<UserDoc>("users");
|
|
486
486
|
const userEntry = (await usersCol.scan({ limit: 1 }))[0];
|
|
487
487
|
const userId = userEntry?.id || "";
|
|
488
|
+
const preference = userEntry?.doc.preferred_cron_channel || "auto";
|
|
488
489
|
|
|
489
490
|
const identitiesCol = await col<UserIdentityDoc>("userIdentities");
|
|
490
491
|
const identityEntries = await identitiesCol.scan({ prefix: `${userId}:` });
|
|
@@ -511,9 +512,9 @@ export async function handleGetCronChannels(
|
|
|
511
512
|
formatted.push({ id: "webchat", type: "webchat", active: true, recommended: true });
|
|
512
513
|
}
|
|
513
514
|
|
|
514
|
-
return addCorsHeaders(Response.json({ channels: formatted }), req);
|
|
515
|
+
return addCorsHeaders(Response.json({ channels: formatted, preference }), req);
|
|
515
516
|
} catch (err) {
|
|
516
517
|
// Non-critical — return empty channels
|
|
517
|
-
return addCorsHeaders(Response.json({ channels: [{ id: "webchat", type: "webchat", active: true, recommended: true }] }), req);
|
|
518
|
+
return addCorsHeaders(Response.json({ channels: [{ id: "webchat", type: "webchat", active: true, recommended: true }], preference: "auto" }), req);
|
|
518
519
|
}
|
|
519
520
|
}
|
|
@@ -22,6 +22,7 @@ export async function handleGetUsers(req: Request, addCorsHeaders: (r: Response,
|
|
|
22
22
|
timezone: u.doc.timezone,
|
|
23
23
|
occupation: u.doc.occupation,
|
|
24
24
|
notes: u.doc.notes,
|
|
25
|
+
preferred_cron_channel: u.doc.preferred_cron_channel,
|
|
25
26
|
createdAt: new Date(u.doc.created_at * 1000).toISOString(),
|
|
26
27
|
agentCount: agentCountByUser.get(u.doc.id) || 0,
|
|
27
28
|
}))
|