agent-mockingbird 0.0.1
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/.agents/skills/btca-cli/SKILL.md +64 -0
- package/.agents/skills/btca-cli/agents/openai.yaml +3 -0
- package/.agents/skills/frontend-design/SKILL.md +42 -0
- package/.agents/skills/frontend-design/agents/openai.yaml +3 -0
- package/.env.example +36 -0
- package/.githooks/pre-commit +33 -0
- package/.github/workflows/ci.yml +309 -0
- package/.opencode/bun.lock +18 -0
- package/.opencode/package.json +5 -0
- package/.opencode/tools/agent_type_manager.ts +100 -0
- package/.opencode/tools/config_manager.ts +87 -0
- package/.opencode/tools/cron_manager.ts +145 -0
- package/.opencode/tools/memory_get.ts +43 -0
- package/.opencode/tools/memory_remember.ts +53 -0
- package/.opencode/tools/memory_search.ts +48 -0
- package/AGENTS.md +126 -0
- package/MEMORY.md +2 -0
- package/README.md +451 -0
- package/THIRD_PARTY_NOTICES.md +11 -0
- package/agent-mockingbird.config.example.json +135 -0
- package/apps/server/package.json +32 -0
- package/apps/server/src/backend/agents/bootstrapContext.ts +362 -0
- package/apps/server/src/backend/agents/openclawImport.test.ts +133 -0
- package/apps/server/src/backend/agents/openclawImport.ts +797 -0
- package/apps/server/src/backend/agents/opencodeConfig.ts +428 -0
- package/apps/server/src/backend/agents/service.ts +10 -0
- package/apps/server/src/backend/config/example-config.test.ts +20 -0
- package/apps/server/src/backend/config/orchestration.ts +243 -0
- package/apps/server/src/backend/config/policy.ts +158 -0
- package/apps/server/src/backend/config/schema.test.ts +15 -0
- package/apps/server/src/backend/config/schema.ts +391 -0
- package/apps/server/src/backend/config/semantic.test.ts +34 -0
- package/apps/server/src/backend/config/semantic.ts +149 -0
- package/apps/server/src/backend/config/service.test.ts +75 -0
- package/apps/server/src/backend/config/service.ts +207 -0
- package/apps/server/src/backend/config/smoke.ts +77 -0
- package/apps/server/src/backend/config/store.test.ts +123 -0
- package/apps/server/src/backend/config/store.ts +581 -0
- package/apps/server/src/backend/config/testFixtures.ts +5 -0
- package/apps/server/src/backend/config/types.ts +56 -0
- package/apps/server/src/backend/contracts/events.ts +320 -0
- package/apps/server/src/backend/contracts/runtime.ts +111 -0
- package/apps/server/src/backend/cron/executor.ts +435 -0
- package/apps/server/src/backend/cron/repository.ts +170 -0
- package/apps/server/src/backend/cron/service.ts +660 -0
- package/apps/server/src/backend/cron/storage.ts +92 -0
- package/apps/server/src/backend/cron/types.ts +138 -0
- package/apps/server/src/backend/cron/utils.ts +351 -0
- package/apps/server/src/backend/db/client.ts +20 -0
- package/apps/server/src/backend/db/migrate.ts +40 -0
- package/apps/server/src/backend/db/repository.ts +1762 -0
- package/apps/server/src/backend/db/schema.ts +113 -0
- package/apps/server/src/backend/db/usageDashboard.test.ts +102 -0
- package/apps/server/src/backend/db/wipe.ts +13 -0
- package/apps/server/src/backend/defaults.ts +32 -0
- package/apps/server/src/backend/env.ts +48 -0
- package/apps/server/src/backend/heartbeat/activeHours.ts +45 -0
- package/apps/server/src/backend/heartbeat/defaultJob.ts +88 -0
- package/apps/server/src/backend/heartbeat/heartbeat.test.ts +110 -0
- package/apps/server/src/backend/heartbeat/runtimeService.ts +190 -0
- package/apps/server/src/backend/heartbeat/service.ts +176 -0
- package/apps/server/src/backend/heartbeat/state.test.ts +63 -0
- package/apps/server/src/backend/heartbeat/state.ts +167 -0
- package/apps/server/src/backend/heartbeat/types.ts +54 -0
- package/apps/server/src/backend/http/boundedQueue.test.ts +49 -0
- package/apps/server/src/backend/http/boundedQueue.ts +92 -0
- package/apps/server/src/backend/http/parsers.ts +40 -0
- package/apps/server/src/backend/http/router.ts +61 -0
- package/apps/server/src/backend/http/routes/agentRoutes.ts +67 -0
- package/apps/server/src/backend/http/routes/backgroundRoutes.ts +203 -0
- package/apps/server/src/backend/http/routes/chatRoutes.ts +107 -0
- package/apps/server/src/backend/http/routes/configRoutes.ts +602 -0
- package/apps/server/src/backend/http/routes/cronRoutes.ts +221 -0
- package/apps/server/src/backend/http/routes/dashboardRoutes.ts +308 -0
- package/apps/server/src/backend/http/routes/eventRoutes.ts +7 -0
- package/apps/server/src/backend/http/routes/heartbeatRoutes.test.ts +41 -0
- package/apps/server/src/backend/http/routes/heartbeatRoutes.ts +28 -0
- package/apps/server/src/backend/http/routes/index.ts +101 -0
- package/apps/server/src/backend/http/routes/mcpRoutes.ts +213 -0
- package/apps/server/src/backend/http/routes/memoryRoutes.ts +154 -0
- package/apps/server/src/backend/http/routes/runRoutes.ts +310 -0
- package/apps/server/src/backend/http/routes/runtimeRoutes.ts +197 -0
- package/apps/server/src/backend/http/routes/skillRoutes.ts +112 -0
- package/apps/server/src/backend/http/routes/uiRoutes.test.ts +161 -0
- package/apps/server/src/backend/http/routes/uiRoutes.ts +177 -0
- package/apps/server/src/backend/http/routes/usageRoutes.test.ts +104 -0
- package/apps/server/src/backend/http/routes/usageRoutes.ts +767 -0
- package/apps/server/src/backend/http/schemas.ts +64 -0
- package/apps/server/src/backend/http/sse.ts +144 -0
- package/apps/server/src/backend/integration/backend-core.test.ts +2316 -0
- package/apps/server/src/backend/logging/logger.ts +64 -0
- package/apps/server/src/backend/mcp/service.ts +326 -0
- package/apps/server/src/backend/memory/cli.ts +170 -0
- package/apps/server/src/backend/memory/conceptExpansion.test.ts +28 -0
- package/apps/server/src/backend/memory/conceptExpansion.ts +80 -0
- package/apps/server/src/backend/memory/qmdPort.test.ts +54 -0
- package/apps/server/src/backend/memory/qmdPort.ts +61 -0
- package/apps/server/src/backend/memory/records.test.ts +66 -0
- package/apps/server/src/backend/memory/records.ts +229 -0
- package/apps/server/src/backend/memory/service.ts +2012 -0
- package/apps/server/src/backend/memory/sqliteVec.ts +58 -0
- package/apps/server/src/backend/memory/types.ts +104 -0
- package/apps/server/src/backend/opencode/agentMockingbirdPlugin.test.ts +396 -0
- package/apps/server/src/backend/opencode/client.ts +98 -0
- package/apps/server/src/backend/opencode/models.ts +41 -0
- package/apps/server/src/backend/opencode/systemPrompt.test.ts +146 -0
- package/apps/server/src/backend/opencode/systemPrompt.ts +284 -0
- package/apps/server/src/backend/paths.ts +57 -0
- package/apps/server/src/backend/prompts/service.ts +100 -0
- package/apps/server/src/backend/queue/queue.test.ts +189 -0
- package/apps/server/src/backend/queue/service.ts +177 -0
- package/apps/server/src/backend/queue/types.ts +39 -0
- package/apps/server/src/backend/run/service.ts +576 -0
- package/apps/server/src/backend/run/storage.ts +47 -0
- package/apps/server/src/backend/run/types.ts +44 -0
- package/apps/server/src/backend/runtime/errors.ts +61 -0
- package/apps/server/src/backend/runtime/index.ts +72 -0
- package/apps/server/src/backend/runtime/memoryPromptDedup.test.ts +153 -0
- package/apps/server/src/backend/runtime/memoryPromptDedup.ts +76 -0
- package/apps/server/src/backend/runtime/opencodeRuntime/backgroundMethods.ts +765 -0
- package/apps/server/src/backend/runtime/opencodeRuntime/coreMethods.ts +705 -0
- package/apps/server/src/backend/runtime/opencodeRuntime/eventMethods.ts +503 -0
- package/apps/server/src/backend/runtime/opencodeRuntime/memoryMethods.ts +462 -0
- package/apps/server/src/backend/runtime/opencodeRuntime/promptMethods.ts +1167 -0
- package/apps/server/src/backend/runtime/opencodeRuntime/shared.ts +254 -0
- package/apps/server/src/backend/runtime/opencodeRuntime.test.ts +2899 -0
- package/apps/server/src/backend/runtime/opencodeRuntime.ts +135 -0
- package/apps/server/src/backend/runtime/sessionScope.ts +45 -0
- package/apps/server/src/backend/skills/service.ts +442 -0
- package/apps/server/src/backend/workspace/resolve.ts +27 -0
- package/apps/server/src/cli/agent-mockingbird.mjs +2522 -0
- package/apps/server/src/cli/agent-mockingbird.test.ts +68 -0
- package/apps/server/src/cli/runtime-assets.mjs +269 -0
- package/apps/server/src/cli/runtime-assets.test.ts +52 -0
- package/apps/server/src/cli/runtime-layout.mjs +75 -0
- package/apps/server/src/cli/standaloneBuild.test.ts +19 -0
- package/apps/server/src/cli/standaloneBuild.ts +19 -0
- package/apps/server/src/cli/standaloneCronBinary.test.ts +187 -0
- package/apps/server/src/index.ts +178 -0
- package/apps/server/tsconfig.json +12 -0
- package/backlog.md +5 -0
- package/bin/agent-mockingbird +2522 -0
- package/bin/runtime-layout.mjs +75 -0
- package/build-bin.ts +34 -0
- package/build-cli.mjs +37 -0
- package/build.ts +40 -0
- package/bun-env.d.ts +11 -0
- package/bun.lock +888 -0
- package/bunfig.toml +2 -0
- package/components.json +21 -0
- package/config.json +130 -0
- package/deploy/RELEASE_INSTALL.md +112 -0
- package/deploy/docker-compose.yml +42 -0
- package/deploy/systemd/README.md +46 -0
- package/deploy/systemd/agent-mockingbird.service +28 -0
- package/deploy/systemd/opencode.service +25 -0
- package/docs/legacy-config-ui-reference.md +51 -0
- package/docs/memory-e2e-trace-2026-03-04.md +63 -0
- package/docs/memory-ops.md +96 -0
- package/docs/memory-runtime-contract.md +42 -0
- package/docs/memory-tuning-remote-2026-03-04.md +59 -0
- package/docs/opencode-rebase-workflow-plan.md +614 -0
- package/docs/opencode-startup-sync-plan.md +94 -0
- package/docs/vendor-opencode.md +41 -0
- package/drizzle/0000_famous_turbo.sql +49 -0
- package/drizzle/0001_cron_memory_aux.sql +160 -0
- package/drizzle/0002_runtime_session_bindings.sql +28 -0
- package/drizzle/0003_background_runs.sql +27 -0
- package/drizzle/0004_memory_open_write.sql +63 -0
- package/drizzle/0005_signal_channel.sql +47 -0
- package/drizzle/0006_usage_event_dimensions.sql +7 -0
- package/drizzle/meta/0000_snapshot.json +341 -0
- package/drizzle/meta/_journal.json +55 -0
- package/drizzle.config.ts +14 -0
- package/eslint.config.mjs +77 -0
- package/knip.json +18 -0
- package/memory/2026-03-04.md +4 -0
- package/opencode.lock.json +16 -0
- package/package.json +67 -0
- package/packages/agent-mockingbird-installer/README.md +31 -0
- package/packages/agent-mockingbird-installer/bin/agent-mockingbird-installer.mjs +44 -0
- package/packages/agent-mockingbird-installer/opencode.lock.json +16 -0
- package/packages/agent-mockingbird-installer/package.json +23 -0
- package/packages/contracts/package.json +19 -0
- package/packages/contracts/src/agentTypes.ts +122 -0
- package/packages/contracts/src/cron.ts +146 -0
- package/packages/contracts/src/dashboard.ts +378 -0
- package/packages/contracts/src/index.ts +3 -0
- package/packages/contracts/tsconfig.json +4 -0
- package/patches/opencode/0001-Wafflebot-OpenCode-baseline.patch +2341 -0
- package/patches/opencode/0002-Fix-OpenCode-web-entry-and-settings-icons.patch +104 -0
- package/patches/opencode/0003-fix-app-remove-duplicate-sidebar-mount.patch +32 -0
- package/patches/opencode/0004-Add-heartbeat-settings-and-usage-nav.patch +506 -0
- package/patches/opencode/0005-Use-chart-icon-for-usage-nav.patch +38 -0
- package/patches/opencode/0006-Modernize-cron-settings.patch +399 -0
- package/patches/opencode/0007-Rename-waffle-namespaces-to-mockingbird.patch +1110 -0
- package/patches/opencode/0008-Remove-cron-contract-section.patch +178 -0
- package/patches/opencode/0009-Rework-cron-tab-as-operations-console.patch +414 -0
- package/patches/opencode/0010-Refine-heartbeat-settings-controls.patch +208 -0
- package/runtime-assets/opencode-config/opencode.jsonc +25 -0
- package/runtime-assets/opencode-config/package.json +5 -0
- package/runtime-assets/opencode-config/plugins/agent-mockingbird.ts +715 -0
- package/runtime-assets/workspace/.agents/skills/config-auditor/SKILL.md +25 -0
- package/runtime-assets/workspace/.agents/skills/config-editor/SKILL.md +24 -0
- package/runtime-assets/workspace/.agents/skills/cron-manager/SKILL.md +57 -0
- package/runtime-assets/workspace/.agents/skills/memory-ops/SKILL.md +120 -0
- package/runtime-assets/workspace/.agents/skills/runtime-diagnose/SKILL.md +25 -0
- package/runtime-assets/workspace/AGENTS.md +56 -0
- package/runtime-assets/workspace/MEMORY.md +4 -0
- package/scripts/build-release-bundle.sh +66 -0
- package/scripts/check-ship.ts +383 -0
- package/scripts/dev-opencode.sh +17 -0
- package/scripts/dev-stack-opencode.sh +15 -0
- package/scripts/dev-stack.sh +61 -0
- package/scripts/install-systemd.sh +87 -0
- package/scripts/memory-e2e.sh +76 -0
- package/scripts/memory-trace-e2e.sh +141 -0
- package/scripts/migrate-opencode-env.ts +108 -0
- package/scripts/onboard/bootstrap.sh +32 -0
- package/scripts/opencode-swap.ts +78 -0
- package/scripts/opencode-sync.ts +715 -0
- package/scripts/runtime-assets-sync.mjs +83 -0
- package/scripts/setup-git-hooks.ts +39 -0
- package/tsconfig.json +45 -0
- package/tui.json +98 -0
- package/turbo.json +36 -0
- package/vendor/OPENCODE_VENDOR.md +13 -0
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { pathToFileURL } from "node:url";
|
|
2
|
+
|
|
3
|
+
import { insertStep } from "./repository";
|
|
4
|
+
import type {
|
|
5
|
+
CronConditionalModule,
|
|
6
|
+
CronConditionalModuleContext,
|
|
7
|
+
CronHandlerResult,
|
|
8
|
+
CronJobDefinition,
|
|
9
|
+
CronJobInstance,
|
|
10
|
+
CronStepKind,
|
|
11
|
+
} from "./types";
|
|
12
|
+
import {
|
|
13
|
+
buildAgentPromptContext,
|
|
14
|
+
computeBackoffMs,
|
|
15
|
+
definitionPayloadContext,
|
|
16
|
+
normalizeConditionalModuleResult,
|
|
17
|
+
nowMs,
|
|
18
|
+
renderTemplate,
|
|
19
|
+
resolveConditionModuleAbsolutePath,
|
|
20
|
+
} from "./utils";
|
|
21
|
+
import { getConfigSnapshot } from "../config/service";
|
|
22
|
+
import type { RuntimeEngine } from "../contracts/runtime";
|
|
23
|
+
import { sqlite } from "../db/client";
|
|
24
|
+
import { getSessionById, setSessionModel, setSessionTitle } from "../db/repository";
|
|
25
|
+
|
|
26
|
+
interface CronExecutorAdapter {
|
|
27
|
+
getJob(jobId: string): Promise<CronJobDefinition | null>;
|
|
28
|
+
loadDefinitionRow(jobId: string): {
|
|
29
|
+
id: string;
|
|
30
|
+
job_definition_id?: never;
|
|
31
|
+
max_attempts: number;
|
|
32
|
+
retry_backoff_ms: number;
|
|
33
|
+
} | null;
|
|
34
|
+
setInstanceState(input: {
|
|
35
|
+
instanceId: string;
|
|
36
|
+
state: "failed" | "completed" | "dead";
|
|
37
|
+
attempt?: number;
|
|
38
|
+
nextAttemptAt?: number | null;
|
|
39
|
+
resultSummary?: string | null;
|
|
40
|
+
error?: unknown;
|
|
41
|
+
}): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class CronExecutor {
|
|
45
|
+
constructor(
|
|
46
|
+
private runtime: RuntimeEngine,
|
|
47
|
+
private adapter: {
|
|
48
|
+
getJob(jobId: string): Promise<CronJobDefinition | null>;
|
|
49
|
+
setInstanceState: CronExecutorAdapter["setInstanceState"];
|
|
50
|
+
},
|
|
51
|
+
) {}
|
|
52
|
+
|
|
53
|
+
async ensureCronThread(definition: CronJobDefinition): Promise<CronJobDefinition> {
|
|
54
|
+
if (definition.threadSessionId) {
|
|
55
|
+
const existingThread = getSessionById(definition.threadSessionId);
|
|
56
|
+
if (existingThread) {
|
|
57
|
+
const mainSession = getSessionById("main");
|
|
58
|
+
const desiredTitle = `Cron: ${definition.name}`;
|
|
59
|
+
if (existingThread.title !== desiredTitle) {
|
|
60
|
+
setSessionTitle(existingThread.id, desiredTitle);
|
|
61
|
+
}
|
|
62
|
+
if (mainSession && existingThread.model !== mainSession.model) {
|
|
63
|
+
setSessionModel(existingThread.id, mainSession.model);
|
|
64
|
+
}
|
|
65
|
+
return (await this.adapter.getJob(definition.id)) ?? definition;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!this.runtime.spawnBackgroundSession) {
|
|
70
|
+
throw new Error("runtime does not support cron thread sessions");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const spawned = await this.runtime.spawnBackgroundSession({
|
|
74
|
+
parentSessionId: "main",
|
|
75
|
+
title: `Cron: ${definition.name}`,
|
|
76
|
+
requestedBy: `cron:${definition.id}`,
|
|
77
|
+
prompt: "",
|
|
78
|
+
});
|
|
79
|
+
const threadSessionId = spawned.childSessionId?.trim();
|
|
80
|
+
if (!threadSessionId) {
|
|
81
|
+
throw new Error("Failed to create cron thread session");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
sqlite
|
|
85
|
+
.query(
|
|
86
|
+
`
|
|
87
|
+
UPDATE cron_job_definitions
|
|
88
|
+
SET thread_session_id = ?2, updated_at = ?3
|
|
89
|
+
WHERE id = ?1
|
|
90
|
+
`,
|
|
91
|
+
)
|
|
92
|
+
.run(definition.id, threadSessionId, nowMs());
|
|
93
|
+
|
|
94
|
+
const mainSession = getSessionById("main");
|
|
95
|
+
if (mainSession) {
|
|
96
|
+
setSessionModel(threadSessionId, mainSession.model);
|
|
97
|
+
}
|
|
98
|
+
setSessionTitle(threadSessionId, `Cron: ${definition.name}`);
|
|
99
|
+
|
|
100
|
+
const refreshed = await this.adapter.getJob(definition.id);
|
|
101
|
+
if (!refreshed) {
|
|
102
|
+
throw new Error(`Unknown cron job: ${definition.id}`);
|
|
103
|
+
}
|
|
104
|
+
return refreshed;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async invokeAgent(input: {
|
|
108
|
+
definition: CronJobDefinition;
|
|
109
|
+
instance: CronJobInstance;
|
|
110
|
+
prompt: string;
|
|
111
|
+
context?: Record<string, unknown>;
|
|
112
|
+
}): Promise<{ ok: true; summary: string } | { ok: false; error: string }> {
|
|
113
|
+
const promptText = input.prompt.trim();
|
|
114
|
+
if (!promptText) return { ok: false, error: "agent prompt was empty" };
|
|
115
|
+
const definition = await this.ensureCronThread(input.definition);
|
|
116
|
+
const targetSession = definition.threadSessionId;
|
|
117
|
+
if (!targetSession) {
|
|
118
|
+
return { ok: false, error: "cron thread session was not created" };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const agentFromPayload =
|
|
122
|
+
typeof input.definition.payload.agentId === "string"
|
|
123
|
+
? input.definition.payload.agentId.trim()
|
|
124
|
+
: typeof input.definition.payload.agent === "string"
|
|
125
|
+
? input.definition.payload.agent.trim()
|
|
126
|
+
: "";
|
|
127
|
+
const expanded = renderTemplate(
|
|
128
|
+
promptText,
|
|
129
|
+
buildAgentPromptContext(definition, input.instance, input.context),
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
const ack = await this.runtime.sendUserMessage({
|
|
134
|
+
sessionId: targetSession,
|
|
135
|
+
content: expanded,
|
|
136
|
+
agent: agentFromPayload || undefined,
|
|
137
|
+
});
|
|
138
|
+
const assistant = [...ack.messages]
|
|
139
|
+
.reverse()
|
|
140
|
+
.find((message) => message.role === "assistant");
|
|
141
|
+
return {
|
|
142
|
+
ok: true,
|
|
143
|
+
summary: assistant?.content?.slice(0, 300) ?? "agent invocation completed",
|
|
144
|
+
};
|
|
145
|
+
} catch (error) {
|
|
146
|
+
const message = error instanceof Error ? error.message : "agent invocation failed";
|
|
147
|
+
return { ok: false, error: message };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async runModuleStep(
|
|
152
|
+
definition: CronJobDefinition,
|
|
153
|
+
instance: CronJobInstance,
|
|
154
|
+
input: { allowAgentInvocation: boolean },
|
|
155
|
+
): Promise<CronHandlerResult> {
|
|
156
|
+
const conditionModulePath = definition.conditionModulePath?.trim();
|
|
157
|
+
if (!conditionModulePath) {
|
|
158
|
+
return {
|
|
159
|
+
status: "error",
|
|
160
|
+
summary: "missing conditionModulePath",
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
let absoluteModulePath = "";
|
|
165
|
+
try {
|
|
166
|
+
absoluteModulePath = resolveConditionModuleAbsolutePath(conditionModulePath);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return {
|
|
169
|
+
status: "error",
|
|
170
|
+
summary: error instanceof Error ? error.message : "invalid conditionModulePath",
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
const result = await this.runConditionalModuleInWorker(absoluteModulePath, {
|
|
176
|
+
nowMs: nowMs(),
|
|
177
|
+
payload: definition.payload,
|
|
178
|
+
job: definition,
|
|
179
|
+
instance,
|
|
180
|
+
});
|
|
181
|
+
if (!input.allowAgentInvocation && result.invokeAgent?.shouldInvoke) {
|
|
182
|
+
return {
|
|
183
|
+
status: "error",
|
|
184
|
+
summary: "runMode=background does not allow invokeAgent",
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return result;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
return {
|
|
190
|
+
status: "error",
|
|
191
|
+
summary: error instanceof Error ? error.message : "conditional module failed",
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async runConditionalModuleInWorker(
|
|
197
|
+
absoluteModulePath: string,
|
|
198
|
+
ctx: CronConditionalModuleContext,
|
|
199
|
+
): Promise<CronHandlerResult> {
|
|
200
|
+
const timeoutMs = getConfigSnapshot().config.runtime.cron.conditionalModuleTimeoutMs;
|
|
201
|
+
const moduleUrl = pathToFileURL(absoluteModulePath).href;
|
|
202
|
+
const task = (async () => {
|
|
203
|
+
const loaded = (await import(`${moduleUrl}?cronRun=${Date.now()}`)) as {
|
|
204
|
+
default?: CronConditionalModule;
|
|
205
|
+
};
|
|
206
|
+
if (typeof loaded.default !== "function") {
|
|
207
|
+
throw new Error("conditional module must export a default function");
|
|
208
|
+
}
|
|
209
|
+
return normalizeConditionalModuleResult(await loaded.default(ctx));
|
|
210
|
+
})();
|
|
211
|
+
|
|
212
|
+
return await Promise.race([
|
|
213
|
+
task,
|
|
214
|
+
new Promise<CronHandlerResult>((_resolve, reject) => {
|
|
215
|
+
setTimeout(() => reject(new Error(`conditional module timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
216
|
+
}),
|
|
217
|
+
]);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async executeInstance(
|
|
221
|
+
claimed: {
|
|
222
|
+
id: string;
|
|
223
|
+
job_definition_id: string;
|
|
224
|
+
attempt: number;
|
|
225
|
+
},
|
|
226
|
+
definition: CronJobDefinition,
|
|
227
|
+
instance: CronJobInstance,
|
|
228
|
+
) {
|
|
229
|
+
const attempt = claimed.attempt + 1;
|
|
230
|
+
const startedAt = nowMs();
|
|
231
|
+
|
|
232
|
+
sqlite
|
|
233
|
+
.query(
|
|
234
|
+
`
|
|
235
|
+
UPDATE cron_job_instances
|
|
236
|
+
SET
|
|
237
|
+
state = 'running',
|
|
238
|
+
attempt = ?2,
|
|
239
|
+
last_heartbeat_at = ?3,
|
|
240
|
+
updated_at = ?3
|
|
241
|
+
WHERE id = ?1
|
|
242
|
+
`,
|
|
243
|
+
)
|
|
244
|
+
.run(claimed.id, attempt, startedAt);
|
|
245
|
+
|
|
246
|
+
let finalSummary = "";
|
|
247
|
+
try {
|
|
248
|
+
definition = await this.ensureCronThread(definition);
|
|
249
|
+
if (definition.runMode === "agent") {
|
|
250
|
+
finalSummary = await this.executeAgentOnlyRun(claimed.id, definition, instance, startedAt);
|
|
251
|
+
} else {
|
|
252
|
+
finalSummary = await this.executeModuleDrivenRun(claimed.id, definition, instance, startedAt);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
this.adapter.setInstanceState({
|
|
256
|
+
instanceId: claimed.id,
|
|
257
|
+
state: "completed",
|
|
258
|
+
attempt,
|
|
259
|
+
resultSummary: finalSummary || "completed",
|
|
260
|
+
});
|
|
261
|
+
} catch (error) {
|
|
262
|
+
const message = error instanceof Error ? error.message : "job execution failed";
|
|
263
|
+
const canRetry = attempt < definition.maxAttempts;
|
|
264
|
+
if (canRetry) {
|
|
265
|
+
this.adapter.setInstanceState({
|
|
266
|
+
instanceId: claimed.id,
|
|
267
|
+
state: "failed",
|
|
268
|
+
attempt,
|
|
269
|
+
nextAttemptAt: nowMs() + computeBackoffMs(definition.retryBackoffMs, attempt),
|
|
270
|
+
error: { message },
|
|
271
|
+
});
|
|
272
|
+
} else {
|
|
273
|
+
this.adapter.setInstanceState({
|
|
274
|
+
instanceId: claimed.id,
|
|
275
|
+
state: "dead",
|
|
276
|
+
attempt,
|
|
277
|
+
error: { message },
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private async executeAgentOnlyRun(
|
|
284
|
+
instanceId: string,
|
|
285
|
+
definition: CronJobDefinition,
|
|
286
|
+
instance: CronJobInstance,
|
|
287
|
+
startedAt: number,
|
|
288
|
+
) {
|
|
289
|
+
const template = definition.agentPromptTemplate ?? "";
|
|
290
|
+
insertStep({
|
|
291
|
+
instanceId,
|
|
292
|
+
stepKind: "agent",
|
|
293
|
+
status: "running",
|
|
294
|
+
input: {
|
|
295
|
+
promptTemplate: definition.agentPromptTemplate,
|
|
296
|
+
payload: definition.payload,
|
|
297
|
+
},
|
|
298
|
+
startedAt,
|
|
299
|
+
});
|
|
300
|
+
const prompt = renderTemplate(template, definitionPayloadContext(definition));
|
|
301
|
+
const agentResult = await this.invokeAgent({
|
|
302
|
+
definition,
|
|
303
|
+
instance,
|
|
304
|
+
prompt,
|
|
305
|
+
});
|
|
306
|
+
if (!agentResult.ok) {
|
|
307
|
+
insertStep({
|
|
308
|
+
instanceId,
|
|
309
|
+
stepKind: "agent",
|
|
310
|
+
status: "failed",
|
|
311
|
+
input: { promptTemplate: template },
|
|
312
|
+
error: { message: agentResult.error },
|
|
313
|
+
startedAt,
|
|
314
|
+
finishedAt: nowMs(),
|
|
315
|
+
});
|
|
316
|
+
throw new Error(agentResult.error);
|
|
317
|
+
}
|
|
318
|
+
insertStep({
|
|
319
|
+
instanceId,
|
|
320
|
+
stepKind: "agent",
|
|
321
|
+
status: "completed",
|
|
322
|
+
input: { promptTemplate: template },
|
|
323
|
+
output: { summary: agentResult.summary },
|
|
324
|
+
startedAt,
|
|
325
|
+
finishedAt: nowMs(),
|
|
326
|
+
});
|
|
327
|
+
return agentResult.summary;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private async executeModuleDrivenRun(
|
|
331
|
+
instanceId: string,
|
|
332
|
+
definition: CronJobDefinition,
|
|
333
|
+
instance: CronJobInstance,
|
|
334
|
+
startedAt: number,
|
|
335
|
+
) {
|
|
336
|
+
const stepKind: CronStepKind =
|
|
337
|
+
definition.runMode === "background" ? "background" : "conditional_agent";
|
|
338
|
+
insertStep({
|
|
339
|
+
instanceId,
|
|
340
|
+
stepKind,
|
|
341
|
+
status: "running",
|
|
342
|
+
input: {
|
|
343
|
+
payload: definition.payload,
|
|
344
|
+
conditionModulePath: definition.conditionModulePath,
|
|
345
|
+
},
|
|
346
|
+
startedAt,
|
|
347
|
+
});
|
|
348
|
+
const moduleResult = await this.runModuleStep(definition, instance, {
|
|
349
|
+
allowAgentInvocation: definition.runMode === "conditional_agent",
|
|
350
|
+
});
|
|
351
|
+
if (moduleResult.status !== "ok") {
|
|
352
|
+
insertStep({
|
|
353
|
+
instanceId,
|
|
354
|
+
stepKind,
|
|
355
|
+
status: "failed",
|
|
356
|
+
input: {
|
|
357
|
+
payload: definition.payload,
|
|
358
|
+
conditionModulePath: definition.conditionModulePath,
|
|
359
|
+
},
|
|
360
|
+
output: moduleResult,
|
|
361
|
+
error: { message: moduleResult.summary ?? "module failed" },
|
|
362
|
+
startedAt,
|
|
363
|
+
finishedAt: nowMs(),
|
|
364
|
+
});
|
|
365
|
+
throw new Error(moduleResult.summary ?? "module failed");
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
insertStep({
|
|
369
|
+
instanceId,
|
|
370
|
+
stepKind,
|
|
371
|
+
status: "completed",
|
|
372
|
+
input: {
|
|
373
|
+
payload: definition.payload,
|
|
374
|
+
conditionModulePath: definition.conditionModulePath,
|
|
375
|
+
},
|
|
376
|
+
output: moduleResult,
|
|
377
|
+
startedAt,
|
|
378
|
+
finishedAt: nowMs(),
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
const finalSummary = moduleResult.summary ?? "module step completed";
|
|
382
|
+
if (
|
|
383
|
+
definition.runMode !== "conditional_agent" ||
|
|
384
|
+
moduleResult.invokeAgent?.shouldInvoke !== true
|
|
385
|
+
) {
|
|
386
|
+
return finalSummary;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const template =
|
|
390
|
+
moduleResult.invokeAgent?.prompt ?? definition.agentPromptTemplate ?? "";
|
|
391
|
+
const prompt = renderTemplate(template, {
|
|
392
|
+
...definitionPayloadContext(definition),
|
|
393
|
+
...(moduleResult.invokeAgent?.context ?? {}),
|
|
394
|
+
});
|
|
395
|
+
const agentStartedAt = nowMs();
|
|
396
|
+
insertStep({
|
|
397
|
+
instanceId,
|
|
398
|
+
stepKind: "agent",
|
|
399
|
+
status: "running",
|
|
400
|
+
input: {
|
|
401
|
+
promptTemplate: template,
|
|
402
|
+
invokeAgent: moduleResult.invokeAgent ?? null,
|
|
403
|
+
},
|
|
404
|
+
startedAt: agentStartedAt,
|
|
405
|
+
});
|
|
406
|
+
const agentResult = await this.invokeAgent({
|
|
407
|
+
definition,
|
|
408
|
+
instance,
|
|
409
|
+
prompt,
|
|
410
|
+
context: moduleResult.invokeAgent?.context,
|
|
411
|
+
});
|
|
412
|
+
if (!agentResult.ok) {
|
|
413
|
+
insertStep({
|
|
414
|
+
instanceId,
|
|
415
|
+
stepKind: "agent",
|
|
416
|
+
status: "failed",
|
|
417
|
+
input: { promptTemplate: template },
|
|
418
|
+
error: { message: agentResult.error },
|
|
419
|
+
startedAt: agentStartedAt,
|
|
420
|
+
finishedAt: nowMs(),
|
|
421
|
+
});
|
|
422
|
+
throw new Error(agentResult.error);
|
|
423
|
+
}
|
|
424
|
+
insertStep({
|
|
425
|
+
instanceId,
|
|
426
|
+
stepKind: "agent",
|
|
427
|
+
status: "completed",
|
|
428
|
+
input: { promptTemplate: template },
|
|
429
|
+
output: { summary: agentResult.summary },
|
|
430
|
+
startedAt: agentStartedAt,
|
|
431
|
+
finishedAt: nowMs(),
|
|
432
|
+
});
|
|
433
|
+
return `${finalSummary}; ${agentResult.summary}`;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import type { SQLQueryBindings } from "bun:sqlite";
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
CronJobDefinition,
|
|
5
|
+
CronJobInstance,
|
|
6
|
+
CronJobState,
|
|
7
|
+
CronJobStep,
|
|
8
|
+
CronScheduleKind,
|
|
9
|
+
CronStepKind,
|
|
10
|
+
CronStepStatus,
|
|
11
|
+
} from "./types";
|
|
12
|
+
import { nowMs, parseJson, toIso, createUniqueId } from "./utils";
|
|
13
|
+
import { sqlite } from "../db/client";
|
|
14
|
+
|
|
15
|
+
export interface CronDefinitionRow {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
thread_session_id: string | null;
|
|
19
|
+
enabled: number;
|
|
20
|
+
schedule_kind: CronScheduleKind;
|
|
21
|
+
schedule_expr: string | null;
|
|
22
|
+
every_ms: number | null;
|
|
23
|
+
at_iso: string | null;
|
|
24
|
+
timezone: string | null;
|
|
25
|
+
run_mode: "background" | "conditional_agent" | "agent";
|
|
26
|
+
handler_key: string | null;
|
|
27
|
+
condition_module_path: string | null;
|
|
28
|
+
condition_description: string | null;
|
|
29
|
+
agent_prompt_template: string | null;
|
|
30
|
+
agent_model_override: string | null;
|
|
31
|
+
max_attempts: number;
|
|
32
|
+
retry_backoff_ms: number;
|
|
33
|
+
payload_json: string;
|
|
34
|
+
last_enqueued_for: number | null;
|
|
35
|
+
created_at: number;
|
|
36
|
+
updated_at: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface CronInstanceRow {
|
|
40
|
+
id: string;
|
|
41
|
+
job_definition_id: string;
|
|
42
|
+
scheduled_for: number;
|
|
43
|
+
agent_invoked: number;
|
|
44
|
+
state: CronJobState;
|
|
45
|
+
attempt: number;
|
|
46
|
+
next_attempt_at: number | null;
|
|
47
|
+
lease_owner: string | null;
|
|
48
|
+
lease_expires_at: number | null;
|
|
49
|
+
last_heartbeat_at: number | null;
|
|
50
|
+
result_summary: string | null;
|
|
51
|
+
error_json: string | null;
|
|
52
|
+
created_at: number;
|
|
53
|
+
updated_at: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface CronStepRow {
|
|
57
|
+
id: string;
|
|
58
|
+
job_instance_id: string;
|
|
59
|
+
step_kind: CronStepKind;
|
|
60
|
+
status: CronStepStatus;
|
|
61
|
+
input_json: string | null;
|
|
62
|
+
output_json: string | null;
|
|
63
|
+
error_json: string | null;
|
|
64
|
+
started_at: number | null;
|
|
65
|
+
finished_at: number | null;
|
|
66
|
+
created_at: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function definitionRowToModel(row: CronDefinitionRow): CronJobDefinition {
|
|
70
|
+
return {
|
|
71
|
+
id: row.id,
|
|
72
|
+
name: row.name,
|
|
73
|
+
threadSessionId: row.thread_session_id,
|
|
74
|
+
enabled: row.enabled === 1,
|
|
75
|
+
scheduleKind: row.schedule_kind,
|
|
76
|
+
scheduleExpr: row.schedule_expr,
|
|
77
|
+
everyMs: row.every_ms,
|
|
78
|
+
atIso: row.at_iso,
|
|
79
|
+
timezone: row.timezone,
|
|
80
|
+
runMode: row.run_mode,
|
|
81
|
+
conditionModulePath: row.condition_module_path,
|
|
82
|
+
conditionDescription: row.condition_description,
|
|
83
|
+
agentPromptTemplate: row.agent_prompt_template,
|
|
84
|
+
agentModelOverride: row.agent_model_override,
|
|
85
|
+
maxAttempts: row.max_attempts,
|
|
86
|
+
retryBackoffMs: row.retry_backoff_ms,
|
|
87
|
+
payload: (parseJson(row.payload_json) as Record<string, unknown>) ?? {},
|
|
88
|
+
lastEnqueuedFor: toIso(row.last_enqueued_for),
|
|
89
|
+
createdAt: toIso(row.created_at) ?? new Date(0).toISOString(),
|
|
90
|
+
updatedAt: toIso(row.updated_at) ?? new Date(0).toISOString(),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function instanceRowToModel(row: CronInstanceRow): CronJobInstance {
|
|
95
|
+
return {
|
|
96
|
+
id: row.id,
|
|
97
|
+
jobDefinitionId: row.job_definition_id,
|
|
98
|
+
scheduledFor: toIso(row.scheduled_for) ?? new Date(0).toISOString(),
|
|
99
|
+
agentInvoked: row.agent_invoked === 1,
|
|
100
|
+
state: row.state,
|
|
101
|
+
attempt: row.attempt,
|
|
102
|
+
nextAttemptAt: toIso(row.next_attempt_at),
|
|
103
|
+
leaseOwner: row.lease_owner,
|
|
104
|
+
leaseExpiresAt: toIso(row.lease_expires_at),
|
|
105
|
+
lastHeartbeatAt: toIso(row.last_heartbeat_at),
|
|
106
|
+
resultSummary: row.result_summary,
|
|
107
|
+
error: parseJson(row.error_json),
|
|
108
|
+
createdAt: toIso(row.created_at) ?? new Date(0).toISOString(),
|
|
109
|
+
updatedAt: toIso(row.updated_at) ?? new Date(0).toISOString(),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function stepRowToModel(row: CronStepRow): CronJobStep {
|
|
114
|
+
return {
|
|
115
|
+
id: row.id,
|
|
116
|
+
jobInstanceId: row.job_instance_id,
|
|
117
|
+
stepKind: row.step_kind,
|
|
118
|
+
status: row.status,
|
|
119
|
+
input: parseJson(row.input_json),
|
|
120
|
+
output: parseJson(row.output_json),
|
|
121
|
+
error: parseJson(row.error_json),
|
|
122
|
+
startedAt: toIso(row.started_at),
|
|
123
|
+
finishedAt: toIso(row.finished_at),
|
|
124
|
+
createdAt: toIso(row.created_at) ?? new Date(0).toISOString(),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function selectOne<T>(query: string, ...args: SQLQueryBindings[]): T | null {
|
|
129
|
+
const row = sqlite.query(query).get(...args);
|
|
130
|
+
return (row as T | null) ?? null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function selectAll<T>(query: string, ...args: SQLQueryBindings[]): T[] {
|
|
134
|
+
return sqlite.query(query).all(...args) as T[];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function insertStep(input: {
|
|
138
|
+
instanceId: string;
|
|
139
|
+
stepKind: CronStepKind;
|
|
140
|
+
status: CronStepStatus;
|
|
141
|
+
input: unknown;
|
|
142
|
+
output?: unknown;
|
|
143
|
+
error?: unknown;
|
|
144
|
+
startedAt?: number | null;
|
|
145
|
+
finishedAt?: number | null;
|
|
146
|
+
}) {
|
|
147
|
+
const createdAt = nowMs();
|
|
148
|
+
sqlite
|
|
149
|
+
.query(
|
|
150
|
+
`
|
|
151
|
+
INSERT INTO cron_job_steps (
|
|
152
|
+
id, job_instance_id, step_kind, status, input_json, output_json, error_json,
|
|
153
|
+
started_at, finished_at, created_at
|
|
154
|
+
)
|
|
155
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
|
|
156
|
+
`,
|
|
157
|
+
)
|
|
158
|
+
.run(
|
|
159
|
+
createUniqueId("step"),
|
|
160
|
+
input.instanceId,
|
|
161
|
+
input.stepKind,
|
|
162
|
+
input.status,
|
|
163
|
+
JSON.stringify(input.input ?? {}),
|
|
164
|
+
input.output === undefined ? null : JSON.stringify(input.output),
|
|
165
|
+
input.error === undefined ? null : JSON.stringify(input.error),
|
|
166
|
+
input.startedAt ?? null,
|
|
167
|
+
input.finishedAt ?? null,
|
|
168
|
+
createdAt,
|
|
169
|
+
);
|
|
170
|
+
}
|