@johpaz/hive-agents 0.0.43 → 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.
Files changed (69) hide show
  1. package/README.md +16 -16
  2. package/dist/hive.js +2256 -1837
  3. package/dist/tool-worker.js +30 -0
  4. package/dist/ui/assets/AgentCreateForm-DzaIT-dA.js +1 -0
  5. package/dist/ui/assets/AgentDetailPage-DgqcJceY.js +1 -0
  6. package/dist/ui/assets/AgentNewPage-CNSpoOSA.js +1 -0
  7. package/dist/ui/assets/{AgentsPage-CGQerrQm.js → AgentsPage-BMUJzTD6.js} +1 -1
  8. package/dist/ui/assets/ApiClientPage-Cum_a_3j.js +3 -0
  9. package/dist/ui/assets/{CanvasPage-Bq8cMKEA.js → CanvasPage-o6oCP6uq.js} +4 -4
  10. package/dist/ui/assets/{ChannelsPage-O2s7RXvS.js → ChannelsPage-WrB0zwLq.js} +1 -1
  11. package/dist/ui/assets/DashboardPage-BCd6kNw0.js +6 -0
  12. package/dist/ui/assets/{LoginPage-B8_NhCDi.js → LoginPage-BTxJdFVG.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-DrjHFxGj.js → LogsPage-DVV2eHbh.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-B2OPRLkn.js → MeetingPage-BULIAWzq.js} +1 -1
  15. package/dist/ui/assets/ModelSelector-BMYOChYb.js +1 -0
  16. package/dist/ui/assets/ProvidersPage-BVN5UZrI.js +1 -0
  17. package/dist/ui/assets/{RecoverPage-kVmp-hM5.js → RecoverPage-7YDQysBL.js} +1 -1
  18. package/dist/ui/assets/SettingsPage-CYmpFfDn.js +9 -0
  19. package/dist/ui/assets/SetupPage-Dnmb1Lbv.js +1 -0
  20. package/dist/ui/assets/{WebChatPage-Dg5mE1ex.js → WebChatPage-DmmdFhIC.js} +1 -1
  21. package/dist/ui/assets/{alert-BQRmSe5N.js → alert-B9J6KHmt.js} +1 -1
  22. package/dist/ui/assets/{alert-dialog-CdDNVtq1.js → alert-dialog-KcYQWcJ6.js} +1 -1
  23. package/dist/ui/assets/{badge-Cn2irDlB.js → badge-88dRb4M8.js} +1 -1
  24. package/dist/ui/assets/{dialog-Dlh5z8bZ.js → dialog-Jk4bieO4.js} +1 -1
  25. package/dist/ui/assets/{es-BnP6oQsd.js → es-4I-joeZz.js} +1 -1
  26. package/dist/ui/assets/{index-CpfjkhN8.js → index-Cyw7L0Li.js} +3 -3
  27. package/dist/ui/assets/{label-fxFZcU5G.js → label-B_15zZlR.js} +1 -1
  28. package/dist/ui/assets/useHiveAgentsModelLoad-BnC4jLE-.js +1 -0
  29. package/dist/ui/assets/useProviders-C1xVKLxB.js +1 -0
  30. package/dist/ui/index.html +1 -1
  31. package/package.json +1 -1
  32. package/packages/core/src/agent/goal-runner.ts +31 -2
  33. package/packages/core/src/agent/llm-client.ts +22 -1
  34. package/packages/core/src/agent/proof-packet.ts +59 -0
  35. package/packages/core/src/agent/run-epoch.ts +33 -0
  36. package/packages/core/src/agent/run-store.ts +50 -8
  37. package/packages/core/src/channels/telegram.ts +31 -2
  38. package/packages/core/src/config/loader.ts +34 -0
  39. package/packages/core/src/gateway/durable-queue.ts +49 -4
  40. package/packages/core/src/gateway/job-executors.ts +50 -11
  41. package/packages/core/src/gateway/job-store.ts +142 -4
  42. package/packages/core/src/gateway/routes/cron-api.ts +3 -2
  43. package/packages/core/src/gateway/routes/users.ts +1 -0
  44. package/packages/core/src/gateway/server.ts +24 -2
  45. package/packages/core/src/resilience/retry.ts +95 -0
  46. package/packages/core/src/scheduler/integration.ts +19 -0
  47. package/packages/core/src/storage/bootstrap.ts +3 -0
  48. package/packages/core/src/storage/collections.ts +36 -0
  49. package/packages/core/src/storage/seed.ts +16 -14
  50. package/packages/skills/src/bundled-data.generated.ts +1107 -1107
  51. package/dist/ui/assets/AgentCreateForm-yUipEHs7.js +0 -1
  52. package/dist/ui/assets/AgentDetailPage-JbsD35Ag.js +0 -1
  53. package/dist/ui/assets/AgentNewPage-CJMzvxcC.js +0 -1
  54. package/dist/ui/assets/ApiClientPage-rI7YUUc5.js +0 -3
  55. package/dist/ui/assets/DashboardPage-CR3CyUJ5.js +0 -6
  56. package/dist/ui/assets/ProvidersPage-Vxg6V3cE.js +0 -1
  57. package/dist/ui/assets/SettingsPage-CNdLt5P_.js +0 -9
  58. package/dist/ui/assets/SetupPage-Ci_Zs3BT.js +0 -1
  59. package/dist/ui/assets/cpu-KDy6-FAI.js +0 -1
  60. package/dist/ui/assets/save-hUmZhceG.js +0 -1
  61. package/dist/ui/assets/useHiveAgentsModelLoad-D9gkq-VO.js +0 -1
  62. package/dist/ui/assets/useProviders-Klaz5WFx.js +0 -1
  63. /package/dist/ui/assets/{NotFound-CZGGDBTp.js → NotFound-BIUDlIXU.js} +0 -0
  64. /package/dist/ui/assets/{accordion-BubmDfgS.js → accordion-CnLzKNHK.js} +0 -0
  65. /package/dist/ui/assets/{card-DFKnZ6ky.js → card-CNf6BS2e.js} +0 -0
  66. /package/dist/ui/assets/{format-BwdV8bB5.js → format-DsLPBxvt.js} +0 -0
  67. /package/dist/ui/assets/{progress-BaTQRPPu.js → progress-D5c-Eilm.js} +0 -0
  68. /package/dist/ui/assets/{scroll-area-8uM7g-LF.js → scroll-area-CihOx0cb.js} +0 -0
  69. /package/dist/ui/assets/{tabs-CqK5bFsS.js → tabs-LQidMKRS.js} +0 -0
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-S-ySWqyJ.js";import{_ as t}from"./vendor-charts-Bu2lyBKP.js";import{nn as n}from"./vendor-radix-D6rA7xKY.js";import{o as r}from"./vendor-query-DsWPbQdG.js";import{t as i}from"./utils-3pnRFmFe.js";import{X as a}from"./index-CpfjkhN8.js";var o=e(t(),1),s=r(),c=a(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`),l=o.forwardRef(({className:e,...t},r)=>(0,s.jsx)(n,{ref:r,className:i(c(),e),...t}));l.displayName=n.displayName;export{l as t};
1
+ import{r as e}from"./rolldown-runtime-S-ySWqyJ.js";import{_ as t}from"./vendor-charts-Bu2lyBKP.js";import{nn as n}from"./vendor-radix-D6rA7xKY.js";import{o as r}from"./vendor-query-DsWPbQdG.js";import{t as i}from"./utils-3pnRFmFe.js";import{X as a}from"./index-Cyw7L0Li.js";var o=e(t(),1),s=r(),c=a(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`),l=o.forwardRef(({className:e,...t},r)=>(0,s.jsx)(n,{ref:r,className:i(c(),e),...t}));l.displayName=n.displayName;export{l as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-S-ySWqyJ.js";import{_ as t}from"./vendor-charts-Bu2lyBKP.js";import{r as n}from"./index-Cyw7L0Li.js";var r=e(t(),1),i=2500,a=3e5;function o(){let e=n(e=>e.loadHiveAgentsModel),t=n(e=>e.getHiveAgentsModelStatus),o=(0,r.useRef)(null);return{load:(0,r.useCallback)(async(n,r)=>{o.current&&(o.current.abort=!0);let s={abort:!1};o.current=s;let c=Date.now();try{await e(n,r)}catch{return!1}for(;!s.abort&&Date.now()-c<a;){try{let e=await t();if(e.loaded&&e.model?.name===n)return!0}catch{}await new Promise(e=>setTimeout(e,i))}return!1},[e,t]),cancel:(0,r.useCallback)(()=>{o.current&&=(o.current.abort=!0,null)},[])}}export{o as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./utils-3pnRFmFe.js";import"./index-Cyw7L0Li.js";var t=e(`Cpu`,[[`rect`,{width:`16`,height:`16`,x:`4`,y:`4`,rx:`2`,key:`14l7u7`}],[`rect`,{width:`6`,height:`6`,x:`9`,y:`9`,rx:`1`,key:`5aljv4`}],[`path`,{d:`M15 2v2`,key:`13l42r`}],[`path`,{d:`M15 20v2`,key:`15mkzm`}],[`path`,{d:`M2 15h2`,key:`1gxd5l`}],[`path`,{d:`M2 9h2`,key:`1bbxkp`}],[`path`,{d:`M20 15h2`,key:`19e6y8`}],[`path`,{d:`M20 9h2`,key:`19tzq7`}],[`path`,{d:`M9 2v2`,key:`165o2o`}],[`path`,{d:`M9 20v2`,key:`i2bqo8`}]]);export{t};
@@ -21,7 +21,7 @@
21
21
  <meta name="twitter:title" content="Hive">
22
22
  <meta property="og:description" content="Hive Agents">
23
23
  <meta name="twitter:description" content="Hive Agents">
24
- <script type="module" crossorigin src="/assets/index-CpfjkhN8.js"></script>
24
+ <script type="module" crossorigin src="/assets/index-Cyw7L0Li.js"></script>
25
25
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-S-ySWqyJ.js">
26
26
  <link rel="modulepreload" crossorigin href="/assets/vendor-charts-Bu2lyBKP.js">
27
27
  <link rel="modulepreload" crossorigin href="/assets/vendor-router-gqiZ7xhx.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johpaz/hive-agents",
3
- "version": "0.0.43",
3
+ "version": "0.0.45",
4
4
  "description": "Tu colmena de agentes IA. Local-first. Multi-canal. Open source. Construido desde Colombia para el mundo.",
5
5
  "private": false,
6
6
  "bin": {
@@ -16,11 +16,20 @@
16
16
 
17
17
  import { logger } from "../utils/logger";
18
18
  import { callLLM, type LLMMessage } from "./llm-client";
19
- import { createRun } from "./run-store";
19
+ import { createRun, type AcceptanceCriterion } from "./run-store";
20
20
  import { clearOldToolResults } from "./compaction";
21
21
  import { loadConfig } from "../config/loader";
22
22
  import { getDurableQueue } from "../gateway/durable-queue";
23
23
 
24
+ export type { AcceptanceCriterion } from "./run-store";
25
+
26
+ export interface AcceptanceResult {
27
+ id: string;
28
+ description: string;
29
+ met: boolean;
30
+ evidence: string;
31
+ }
32
+
24
33
  const log = logger.child("goal-runner");
25
34
 
26
35
  const MAX_GOAL_ATTEMPTS = 5;
@@ -36,6 +45,8 @@ export interface GoalRunOptions {
36
45
  maxTurns?: number;
37
46
  maxTokens?: number;
38
47
  maxAttempts?: number;
48
+ /** Whole-job acceptance criteria — when set, the goal is only "met" once every criterion is. */
49
+ acceptance?: AcceptanceCriterion[];
39
50
  }
40
51
 
41
52
  export interface GoalRunResult {
@@ -72,6 +83,7 @@ export async function runGoal(opts: GoalRunOptions): Promise<GoalRunResult> {
72
83
  goal: opts.goal,
73
84
  goal_check_tool: opts.goalCheckTool ?? null,
74
85
  resume_policy: "resume",
86
+ acceptance: opts.acceptance,
75
87
  });
76
88
 
77
89
  // Enqueue a goal_run job in the durable queue
@@ -114,13 +126,30 @@ export async function runGoal(opts: GoalRunOptions): Promise<GoalRunResult> {
114
126
  * Verify whether a goal has been met using either:
115
127
  * - A deterministic tool (goal_check_tool) — executes the tool and checks the result
116
128
  * - An LLM verifier — asks the model to return JSON {met, reason}
129
+ *
130
+ * When `acceptance` criteria are supplied, each is verified independently
131
+ * (its own checkTool, or an LLM judgment against its own description) and
132
+ * the overall verdict is the conjunction of all of them — the top-level
133
+ * `goal`/`checkTool` are ignored in that case.
117
134
  */
118
135
  export async function verifyGoal(
119
136
  goal: string,
120
137
  checkTool: string | null | undefined,
121
138
  messages: LLMMessage[],
122
139
  providerCfg: any,
123
- ): Promise<{ met: boolean; reason: string }> {
140
+ acceptance?: AcceptanceCriterion[] | null,
141
+ ): Promise<{ met: boolean; reason: string; acceptanceResults?: AcceptanceResult[] }> {
142
+ if (acceptance && acceptance.length > 0) {
143
+ const results: AcceptanceResult[] = [];
144
+ for (const criterion of acceptance) {
145
+ const verdict = await verifyGoal(criterion.description, criterion.checkTool, messages, providerCfg);
146
+ results.push({ id: criterion.id, description: criterion.description, met: verdict.met, evidence: verdict.reason });
147
+ }
148
+ const met = results.every((r) => r.met);
149
+ const reason = results.map((r) => `${r.met ? "✅" : "❌"} ${r.description}: ${r.evidence}`).join("\n");
150
+ return { met, reason, acceptanceResults: results };
151
+ }
152
+
124
153
  // If we have a deterministic check tool, execute it
125
154
  if (checkTool) {
126
155
  try {
@@ -12,6 +12,8 @@
12
12
  */
13
13
 
14
14
  import { logger } from "../utils/logger"
15
+ import { loadConfig } from "../config/loader"
16
+ import { withRetry, isRetryableError, type RetryPolicy } from "../resilience/retry"
15
17
  import { GeminiProvider } from "./llm-providers/gemini"
16
18
  import { AnthropicProvider } from "./llm-providers/anthropic"
17
19
  import { OllamaProvider } from "./llm-providers/ollama"
@@ -137,10 +139,29 @@ function getProvider(provider: string): LLMProvider {
137
139
 
138
140
  /**
139
141
  * Call any LLM provider. Returns a canonical LLMResponse regardless of provider.
142
+ *
143
+ * Retries transient failures (429/5xx/timeout/network) with exponential
144
+ * backoff + jitter per `config.retry`, honoring `Retry-After` when the
145
+ * provider sends one. An aborted signal never retries. Note: this retries
146
+ * the whole call, so a failure that happens mid-stream (after onToken has
147
+ * already fired) can produce a duplicated partial response — acceptable
148
+ * because provider failures overwhelmingly happen before the stream starts
149
+ * (auth/rate-limit/connection errors).
140
150
  */
141
151
  export async function callLLM(options: LLMCallOptions): Promise<LLMResponse> {
152
+ const retryCfg = loadConfig().retry
153
+ const policy: RetryPolicy = {
154
+ maxAttempts: retryCfg?.maxAttempts ?? 3,
155
+ initialDelayMs: retryCfg?.initialDelayMs ?? 1000,
156
+ backoffMultiplier: retryCfg?.backoffMultiplier ?? 2,
157
+ maxDelayMs: retryCfg?.maxDelayMs ?? 30000,
158
+ }
142
159
  try {
143
- return await getProvider(options.provider).call(options)
160
+ return await withRetry(
161
+ () => getProvider(options.provider).call(options),
162
+ policy,
163
+ (err) => !options.signal?.aborted && isRetryableError(err)
164
+ )
144
165
  } catch (err) {
145
166
  const msg = (err as Error).message
146
167
  const cleanModel = options.model.replace(new RegExp(`^${options.provider}\\/`), "")
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Proof packets — compressed evidence artifact for a completed goal/project
3
+ * run (harness-engineering "proof" practice): what was intended, what was
4
+ * checked, what evidence backs the verdict, and known limits. Written once
5
+ * per run by the goal_run / project_task executors after verification, so a
6
+ * reviewer doesn't have to replay the whole run to trust its outcome.
7
+ */
8
+
9
+ import { col, nextId } from "../storage/hive";
10
+ import type { ProofPacketDoc } from "../storage/collections";
11
+ import type { AcceptanceResult } from "./goal-runner";
12
+ import type { RunEpoch } from "./run-epoch";
13
+ import { logger } from "../utils/logger";
14
+
15
+ const log = logger.child("proof-packet");
16
+
17
+ export interface BuildProofPacketInput {
18
+ runId: string;
19
+ agentId: string;
20
+ intendedOutcome: string;
21
+ met: boolean;
22
+ /** Per-criterion verdicts when acceptance criteria were set; falls back to a single-entry summary otherwise. */
23
+ acceptanceResults?: AcceptanceResult[];
24
+ checksRun: string[];
25
+ evidence: string[];
26
+ knownLimits?: string | null;
27
+ epoch?: RunEpoch | null;
28
+ }
29
+
30
+ export async function buildProofPacket(input: BuildProofPacketInput): Promise<ProofPacketDoc> {
31
+ const id = await nextId("proofPackets");
32
+ const acceptanceResults: AcceptanceResult[] =
33
+ input.acceptanceResults ?? [{ id: "goal", description: input.intendedOutcome, met: input.met, evidence: input.evidence.join("; ") || "n/a" }];
34
+
35
+ const doc: ProofPacketDoc = {
36
+ id,
37
+ run_id: input.runId,
38
+ agent_id: input.agentId,
39
+ intended_outcome: input.intendedOutcome,
40
+ acceptance_results_json: JSON.stringify(acceptanceResults),
41
+ checks_run_json: JSON.stringify(input.checksRun),
42
+ evidence_json: JSON.stringify(input.evidence),
43
+ known_limits: input.knownLimits ?? null,
44
+ epoch_json: input.epoch ? JSON.stringify(input.epoch) : null,
45
+ met: input.met,
46
+ created_at: Date.now(),
47
+ };
48
+
49
+ const c = await col<ProofPacketDoc>("proofPackets");
50
+ await c.put(id, doc, { expectedVersion: 0 });
51
+ log.info(`[buildProofPacket] Packet ${id} written for run ${input.runId} (met=${input.met})`);
52
+ return doc;
53
+ }
54
+
55
+ export async function findProofPacketsByRun(runId: string): Promise<ProofPacketDoc[]> {
56
+ const c = await col<ProofPacketDoc>("proofPackets");
57
+ const entries = await c.findBy("run_id", runId);
58
+ return entries.map((e) => e.doc);
59
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Fixed-worker epoch (harness-engineering concept): the exact
3
+ * provider/model/app-version/tool-catalog combination a run executed under.
4
+ * A model or tool-catalog change is a requalification signal — proof
5
+ * packets from different epochs shouldn't be compared as if the "worker"
6
+ * were unchanged.
7
+ */
8
+
9
+ import rootPackage from "../../../../package.json";
10
+
11
+ export interface RunEpoch {
12
+ provider: string;
13
+ model: string;
14
+ app_version: string;
15
+ tool_catalog_hash: string;
16
+ }
17
+
18
+ /** Stable non-cryptographic hash (djb2) over sorted tool names — a cheap fingerprint of the active tool catalog. */
19
+ function hashToolNames(names: string[]): string {
20
+ const sorted = [...names].sort().join(",");
21
+ let hash = 5381;
22
+ for (let i = 0; i < sorted.length; i++) hash = ((hash * 33) ^ sorted.charCodeAt(i)) >>> 0;
23
+ return hash.toString(16);
24
+ }
25
+
26
+ export function buildRunEpoch(opts: { provider: string; model: string; toolNames: string[] }): RunEpoch {
27
+ return {
28
+ provider: opts.provider,
29
+ model: opts.model,
30
+ app_version: (rootPackage as { version: string }).version,
31
+ tool_catalog_hash: hashToolNames(opts.toolNames),
32
+ };
33
+ }
@@ -14,15 +14,23 @@ import { col, updateDoc, nextId } from "../storage/hive";
14
14
  import type { AgentRunDoc } from "../storage/collections";
15
15
  import { getBootId } from "../storage/boot-id";
16
16
  import { logger } from "../utils/logger";
17
+ import { loadConfig } from "../config/loader";
17
18
  import type { LLMMessage } from "./llm-client";
19
+ import type { RunEpoch } from "./run-epoch";
18
20
 
19
21
  const log = logger.child("run-store");
20
22
 
21
- const LEASE_RENEW_INTERVAL_MS = 30_000;
22
- const LEASE_DURATION_MS = 2 * 60 * 1000;
23
23
  const MAX_STATE_BYTES = 1_500_000;
24
24
  const MAX_RETRIES = 5;
25
25
 
26
+ function runLeaseDurationMs(): number {
27
+ return loadConfig().harness?.runLeaseMs ?? 2 * 60 * 1000;
28
+ }
29
+
30
+ function leaseRenewIntervalMs(): number {
31
+ return loadConfig().harness?.leaseRenewMs ?? 30_000;
32
+ }
33
+
26
34
  export interface RunCheckpointState {
27
35
  version: 1
28
36
  messages: LLMMessage[]
@@ -36,6 +44,14 @@ export interface RunCheckpointState {
36
44
  systemPromptSkillSections: string[]
37
45
  }
38
46
 
47
+ /** Whole-job acceptance criterion (harness-engineering "proof" concept). */
48
+ export interface AcceptanceCriterion {
49
+ id: string
50
+ description: string
51
+ /** Deterministic tool to check this specific criterion; falls back to LLM judgment when absent. */
52
+ checkTool?: string | null
53
+ }
54
+
39
55
  export interface CreateRunInput {
40
56
  thread_id: string
41
57
  agent_id: string
@@ -48,6 +64,8 @@ export interface CreateRunInput {
48
64
  goal?: string | null
49
65
  goal_check_tool?: string | null
50
66
  resume_policy?: AgentRunDoc["resume_policy"]
67
+ acceptance?: AcceptanceCriterion[]
68
+ epoch?: RunEpoch
51
69
  }
52
70
 
53
71
  export async function createRun(input: CreateRunInput): Promise<AgentRunDoc> {
@@ -76,8 +94,10 @@ export async function createRun(input: CreateRunInput): Promise<AgentRunDoc> {
76
94
  pending_tool_calls_json: null,
77
95
  checkpointed_at: now,
78
96
  boot_id: bootId,
79
- lease_expires_at: now + LEASE_DURATION_MS,
97
+ lease_expires_at: now + runLeaseDurationMs(),
80
98
  resume_policy: input.resume_policy ?? "resume",
99
+ acceptance_json: input.acceptance ? JSON.stringify(input.acceptance) : null,
100
+ epoch_json: input.epoch ? JSON.stringify(input.epoch) : null,
81
101
  error: null,
82
102
  created_at: now,
83
103
  updated_at: now,
@@ -114,7 +134,7 @@ export async function checkpoint(
114
134
  checkpointed_at: Date.now(),
115
135
  iterations_used: state.iterations,
116
136
  tokens_used: state.totalInputTokens + state.totalOutputTokens,
117
- lease_expires_at: Date.now() + LEASE_DURATION_MS,
137
+ lease_expires_at: Date.now() + runLeaseDurationMs(),
118
138
  boot_id: getBootId(),
119
139
  updated_at: Date.now(),
120
140
  };
@@ -131,7 +151,7 @@ export async function bumpTurn(runId: string, tokensDelta: number): Promise<Agen
131
151
  return updateDoc<AgentRunDoc>("agentRuns", runId, {
132
152
  turns_used: existing.turns_used + 1,
133
153
  tokens_used: existing.tokens_used + tokensDelta,
134
- lease_expires_at: Date.now() + LEASE_DURATION_MS,
154
+ lease_expires_at: Date.now() + runLeaseDurationMs(),
135
155
  updated_at: Date.now(),
136
156
  });
137
157
  }
@@ -187,7 +207,7 @@ export async function reclaimRun(runId: string): Promise<void> {
187
207
  await updateDoc<AgentRunDoc>("agentRuns", runId, {
188
208
  status: "running",
189
209
  boot_id: getBootId(),
190
- lease_expires_at: now + LEASE_DURATION_MS,
210
+ lease_expires_at: now + runLeaseDurationMs(),
191
211
  error: null,
192
212
  finished_at: null,
193
213
  updated_at: now,
@@ -221,6 +241,28 @@ export async function findExpiredRuns(): Promise<AgentRunDoc[]> {
221
241
  return running.filter((r) => r.lease_expires_at < now);
222
242
  }
223
243
 
244
+ /** Deserialize acceptance criteria back from AgentRunDoc.acceptance_json, or null if none were set. */
245
+ export function deserializeAcceptance(run: AgentRunDoc): AcceptanceCriterion[] | null {
246
+ if (!run.acceptance_json) return null;
247
+ try {
248
+ return JSON.parse(run.acceptance_json) as AcceptanceCriterion[];
249
+ } catch {
250
+ log.warn(`[deserializeAcceptance] Failed to parse acceptance_json for run ${run.id}`);
251
+ return null;
252
+ }
253
+ }
254
+
255
+ /** Deserialize the fixed-worker epoch back from AgentRunDoc.epoch_json, or null if unset. */
256
+ export function deserializeEpoch(run: AgentRunDoc): RunEpoch | null {
257
+ if (!run.epoch_json) return null;
258
+ try {
259
+ return JSON.parse(run.epoch_json) as RunEpoch;
260
+ } catch {
261
+ log.warn(`[deserializeEpoch] Failed to parse epoch_json for run ${run.id}`);
262
+ return null;
263
+ }
264
+ }
265
+
224
266
  /**
225
267
  * Deserialize a checkpoint back into RunCheckpointState, or null if the
226
268
  * run has no checkpoint (empty state_json — chat runs that never promoted
@@ -308,13 +350,13 @@ export function startLeaseRenewal(runId: string): void {
308
350
  return;
309
351
  }
310
352
  await updateDoc<AgentRunDoc>("agentRuns", runId, {
311
- lease_expires_at: Date.now() + LEASE_DURATION_MS,
353
+ lease_expires_at: Date.now() + runLeaseDurationMs(),
312
354
  updated_at: Date.now(),
313
355
  } as Partial<AgentRunDoc>);
314
356
  } catch (err) {
315
357
  log.warn(`[startLeaseRenewal] Failed to renew lease for ${runId}: ${(err as Error).message}`);
316
358
  }
317
- }, LEASE_RENEW_INTERVAL_MS);
359
+ }, leaseRenewIntervalMs());
318
360
  leaseTimers.set(runId, timer);
319
361
  }
320
362
 
@@ -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.checkExpiredLeases(), LEASE_CHECK_INTERVAL_MS);
158
- log.info(`[start] Lease checker running every ${LEASE_CHECK_INTERVAL_MS}ms`);
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
- await failJob(job.id, result.error ?? "Unknown error", this.bootId);
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
- await failJob(job.id, (err as Error).message, this.bootId);
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();