@aiwg/cli 2026.10.15 → 2026.10.18
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/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
- package/dist/src/artifacts/citation-parser.js +7 -6
- package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
- package/dist/src/artifacts/corpus-tools/cli.js +8 -3
- package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
- package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
- package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
- package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
- package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
- package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
- package/dist/src/artifacts/corpus-tools/expand.js +16 -17
- package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
- package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
- package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
- package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
- package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
- package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
- package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
- package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
- package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
- package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
- package/dist/src/artifacts/graph-query.js +5 -3
- package/dist/src/artifacts/hybrid-query.js +11 -2
- package/dist/src/artifacts/index-refresh.js +2 -0
- package/dist/src/artifacts/query-engine-corpus.js +217 -0
- package/dist/src/artifacts/query-engine-discover-output.js +229 -0
- package/dist/src/artifacts/query-engine-discover.js +285 -0
- package/dist/src/artifacts/query-engine-entries.js +188 -0
- package/dist/src/artifacts/query-engine-index.js +249 -0
- package/dist/src/artifacts/query-engine-matching.js +143 -0
- package/dist/src/artifacts/query-engine-options.js +2 -0
- package/dist/src/artifacts/query-engine-rules.js +202 -0
- package/dist/src/artifacts/query-engine-scoring.js +436 -0
- package/dist/src/artifacts/query-engine-show-card.js +194 -0
- package/dist/src/artifacts/query-engine-show-load.js +211 -0
- package/dist/src/artifacts/query-engine-show.js +300 -0
- package/dist/src/artifacts/query-engine.js +7 -2576
- package/dist/src/cli/handlers/daemon.js +17 -1
- package/dist/src/cli/handlers/doctor-args.js +10 -5
- package/dist/src/cli/handlers/doctor-help.js +4 -1
- package/dist/src/cli/handlers/index.js +2 -2
- package/dist/src/cli/handlers/mc-agents.js +111 -0
- package/dist/src/cli/handlers/mc-args.js +54 -0
- package/dist/src/cli/handlers/mc-control.js +227 -0
- package/dist/src/cli/handlers/mc-dispatch.js +203 -0
- package/dist/src/cli/handlers/mc-help.js +171 -0
- package/dist/src/cli/handlers/mc-run.js +343 -0
- package/dist/src/cli/handlers/mc-session.js +138 -0
- package/dist/src/cli/handlers/mc-status.js +258 -0
- package/dist/src/cli/handlers/mc-summary.js +43 -0
- package/dist/src/cli/handlers/mc-types.js +3 -0
- package/dist/src/cli/handlers/mc-worker.js +205 -0
- package/dist/src/cli/handlers/mc.js +12 -1665
- package/dist/src/cli/handlers/models-refusal.js +13 -0
- package/dist/src/cli/handlers/models-resource-sample.js +10 -0
- package/dist/src/cli/handlers/models.js +5 -3
- package/dist/src/cli/handlers/regenerate.js +8 -16
- package/dist/src/cli/handlers/remove-bundled.js +133 -0
- package/dist/src/cli/handlers/remove-options.js +31 -0
- package/dist/src/cli/handlers/remove-user.js +174 -0
- package/dist/src/cli/handlers/remove.js +201 -0
- package/dist/src/cli/handlers/sessions.js +7 -7
- package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
- package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
- package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
- package/dist/src/cli/handlers/subcommands-list.js +250 -0
- package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
- package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
- package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
- package/dist/src/cli/handlers/subcommands-services.js +66 -0
- package/dist/src/cli/handlers/subcommands-storage.js +259 -0
- package/dist/src/cli/handlers/subcommands.js +18 -1976
- package/dist/src/cli/handlers/update.js +157 -0
- package/dist/src/cli/handlers/use.js +14 -4
- package/dist/src/cli/handlers/utilities.js +3 -560
- package/dist/src/cli/handlers/utility-doctor.js +412 -0
- package/dist/src/cli/scope-resolver.js +1 -142
- package/dist/src/cli/services/deployment-verification.js +0 -1
- package/dist/src/cli/user-scope-mirror.js +173 -0
- package/dist/src/config/aiwg-config.js +2 -1
- package/dist/src/config/authorization-cli.js +7 -3
- package/dist/src/config/dispatch-host-thresholds.js +2 -0
- package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
- package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
- package/dist/src/config/framework-aliases.js +12 -0
- package/dist/src/config/host-resource-report.d.mts +24 -0
- package/dist/src/config/host-resource-report.mjs +110 -0
- package/dist/src/config/host-resource-runtime.d.mts +37 -0
- package/dist/src/config/host-resource-runtime.mjs +296 -0
- package/dist/src/config/installed-selection.js +22 -0
- package/dist/src/config/worker-invocation-marker.d.mts +1 -0
- package/dist/src/config/worker-invocation-marker.mjs +2 -0
- package/dist/src/decision/ensemble-study/artifacts.js +7 -0
- package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
- package/dist/src/decision/ensemble-study/gates.js +78 -0
- package/dist/src/decision/ensemble-study/protocol.js +18 -21
- package/dist/src/decision/ensemble-study/score.js +3 -2
- package/dist/src/decision/ensemble-study/statistics.js +7 -26
- package/dist/src/decision/heldout/access.js +74 -0
- package/dist/src/decision/heldout/calibration.js +1 -0
- package/dist/src/decision/heldout/collector.js +8 -1
- package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
- package/dist/src/decision/sensitivity/comparative.js +18 -41
- package/dist/src/effects/verifiers/file.js +22 -5
- package/dist/src/extensions/claude-attribution.js +82 -0
- package/dist/src/extensions/claude-hooks-installer.js +133 -69
- package/dist/src/extensions/commands/daemon.js +109 -0
- package/dist/src/extensions/commands/definitions.js +5 -89
- package/dist/src/gates/evaluate.js +2 -358
- package/dist/src/gates/heldout.js +17 -7
- package/dist/src/gates/observations.js +363 -0
- package/dist/src/gates/pack-composition.js +270 -0
- package/dist/src/gates/pack-tightening.js +197 -0
- package/dist/src/gates/pack-validation.js +262 -0
- package/dist/src/gates/registry-error.js +5 -0
- package/dist/src/gates/registry.js +13 -685
- package/dist/src/lint/check-patterns.js +163 -0
- package/dist/src/lint/checks.js +268 -0
- package/dist/src/lint/reference-resolution.js +54 -0
- package/dist/src/lint/runner.js +3 -465
- package/dist/src/mcp/helpers.mjs +11 -1
- package/dist/src/mcp/json-document.mjs +29 -0
- package/dist/src/mcp/muse-native-config.mjs +1 -28
- package/dist/src/memory/project-registry.js +44 -4
- package/dist/src/mission-protocol/worker-review-gate.js +7 -0
- package/dist/src/models/worker-plan.js +36 -5
- package/dist/src/models/wrapper-deployment.js +25 -12
- package/dist/src/models/wrapper-enforcement.js +47 -7
- package/dist/src/network-analysis/research.js +2 -1
- package/dist/src/plugin/command-ownership.js +34 -0
- package/dist/src/plugin/skill-command-frontmatter.js +197 -0
- package/dist/src/plugin/skill-command-translator.js +6 -232
- package/dist/src/policy/hitl-check.js +14 -4
- package/dist/src/policy/hitl-consume.js +54 -0
- package/dist/src/policy/hitl-receipt.js +2 -0
- package/dist/src/policy/hitl.js +11 -3
- package/dist/src/providers/context-output-ownership.js +26 -0
- package/dist/src/providers/deployment-ownership.d.mts +19 -0
- package/dist/src/providers/deployment-ownership.mjs +226 -0
- package/dist/src/providers/deployment-removal.js +200 -0
- package/dist/src/providers/provider-context-contracts.js +162 -0
- package/dist/src/providers/provider-definition-schema.js +136 -0
- package/dist/src/providers/provider-definitions.js +8 -1298
- package/dist/src/providers/provider-seeds-1.js +360 -0
- package/dist/src/providers/provider-seeds-2.js +387 -0
- package/dist/src/providers/provider-seeds-3.js +262 -0
- package/dist/src/providers/removal-transaction.js +86 -0
- package/dist/src/providers/settings-document.d.mts +3 -0
- package/dist/src/providers/settings-document.mjs +47 -0
- package/dist/src/providers/settings-removal.js +190 -0
- package/dist/src/providers/skill-ownership.d.mts +19 -2
- package/dist/src/providers/skill-ownership.mjs +12 -4
- package/dist/src/providers/transformation-receipt-integration.js +15 -271
- package/dist/src/providers/transformation-receipt-outputs.js +99 -0
- package/dist/src/providers/transformation-receipt-source.js +194 -0
- package/dist/src/research/clients/arxiv.js +4 -30
- package/dist/src/research/clients/base.js +48 -22
- package/dist/src/research/identity.js +42 -4
- package/dist/src/research/query-cli.js +3 -87
- package/dist/src/research/query-options.js +87 -0
- package/dist/src/research/reference-match.js +105 -24
- package/dist/src/research/services/acquisition.js +9 -7
- package/dist/src/research/services/citation.js +5 -2
- package/dist/src/research/types.js +2 -0
- package/dist/src/rules/activation.mjs +15 -6
- package/dist/src/rules/core-startup.mjs +2 -2
- package/dist/src/serve/mission-conductor.js +52 -4
- package/dist/src/serve/mission-summary.js +56 -0
- package/dist/src/sessions/adapters/grok-build-native.js +23 -0
- package/dist/src/sessions/adapters/grok-build.js +14 -7
- package/dist/src/sessions/workspace-discovery.js +5 -5
- package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
- package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
- package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
- package/dist/src/smiths/context-pipeline/finalization.js +81 -51
- package/dist/src/smiths/context-pipeline/generator.js +10 -11
- package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
- package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
- package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
- package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
- package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
- package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
- package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
- package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
- package/dist/src/smiths/hook-bridge/index.js +9 -0
- package/package.json +13 -1
- package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
- package/schemas/decision/D29Study.v10.schema.json +65 -0
- package/tools/agents/deploy-agents.mjs +24 -675
- package/tools/agents/deploy-command-mirrors.mjs +229 -0
- package/tools/agents/deploy-options.mjs +258 -0
- package/tools/agents/deploy-support.mjs +165 -0
- package/tools/agents/providers/base-addon-discovery.mjs +139 -0
- package/tools/agents/providers/base-behaviors.mjs +168 -0
- package/tools/agents/providers/base-context.mjs +205 -0
- package/tools/agents/providers/base-contract.mjs +116 -0
- package/tools/agents/providers/base-files.mjs +252 -0
- package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
- package/tools/agents/providers/base-framework-discovery.mjs +309 -0
- package/tools/agents/providers/base-frontmatter.mjs +196 -0
- package/tools/agents/providers/base-inventory.mjs +269 -0
- package/tools/agents/providers/base-kernel-skills.mjs +354 -0
- package/tools/agents/providers/base-migrations.mjs +258 -0
- package/tools/agents/providers/base-models-platforms.mjs +273 -0
- package/tools/agents/providers/base-rule-index.mjs +450 -0
- package/tools/agents/providers/base-runtime.mjs +60 -0
- package/tools/agents/providers/base-skill-copy.mjs +273 -0
- package/tools/agents/providers/base.mjs +16 -3364
- package/tools/agents/providers/claude-post-deploy.mjs +20 -1
- package/tools/agents/providers/context-write.mjs +4 -0
- package/tools/agents/providers/hermes-startup.mjs +0 -5
- package/tools/agents/providers/muse.mjs +7 -2
- package/tools/agents/providers/pi.mjs +3 -1
- package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
- package/tools/agents/providers/rule-delivery.mjs +20 -1144
- package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
- package/tools/agents/providers/rule-deployment-state.mjs +300 -0
- package/tools/agents/providers/rule-projection.mjs +3 -0
- package/tools/daemon/README.md +511 -0
- package/tools/daemon/adapters/base-adapter.mjs +84 -0
- package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
- package/tools/daemon/agent-supervisor.mjs +299 -0
- package/tools/daemon/automation-engine.mjs +310 -0
- package/tools/daemon/autonomous-engine.mjs +346 -0
- package/tools/daemon/behavior-loader.mjs +316 -0
- package/tools/daemon/behavior.mjs +174 -0
- package/tools/daemon/concierge/intent-router.mjs +401 -0
- package/tools/daemon/concierge/orchestrator.mjs +272 -0
- package/tools/daemon/concierge/response-translator.mjs +462 -0
- package/tools/daemon/config.mjs +377 -0
- package/tools/daemon/cron-scheduler.mjs +178 -0
- package/tools/daemon/daemon-main.mjs +1169 -0
- package/tools/daemon/event-router.mjs +84 -0
- package/tools/daemon/file-watcher.mjs +383 -0
- package/tools/daemon/index.mjs +1181 -0
- package/tools/daemon/init-profile.mjs +124 -0
- package/tools/daemon/ipc-client.mjs +197 -0
- package/tools/daemon/ipc-ops-handlers.mjs +236 -0
- package/tools/daemon/ipc-server.mjs +275 -0
- package/tools/daemon/maintenance-owner.mjs +79 -0
- package/tools/daemon/memory-manager.mjs +386 -0
- package/tools/daemon/message-router.mjs +194 -0
- package/tools/daemon/provider-watcher.mjs +585 -0
- package/tools/daemon/pty-adapter.mjs +420 -0
- package/tools/daemon/repl-chat.mjs +359 -0
- package/tools/daemon/resource-bounds.mjs +88 -0
- package/tools/daemon/sandbox-transport.mjs +295 -0
- package/tools/daemon/scheduled-task-runner.mjs +535 -0
- package/tools/daemon/task-store.mjs +450 -0
- package/tools/daemon/tmux-manager.mjs +324 -0
- package/tools/daemon/update-policy.mjs +517 -0
- package/tools/daemon/web-server.mjs +399 -0
- package/tools/daemon/web-ui/index.html +585 -0
- package/tools/daemon/web-ui/styles.css +156 -0
- package/tools/docker/Dockerfile.daemon +35 -0
- package/tools/docker/container-manager.mjs +291 -0
- package/tools/messaging/adapter-registry.mjs +230 -0
- package/tools/messaging/adapters/base.mjs +326 -0
- package/tools/messaging/adapters/discord.mjs +462 -0
- package/tools/messaging/adapters/slack.mjs +402 -0
- package/tools/messaging/adapters/telegram.mjs +552 -0
- package/tools/messaging/chat-handler.mjs +297 -0
- package/tools/messaging/command-router.mjs +269 -0
- package/tools/messaging/event-bus.mjs +199 -0
- package/tools/messaging/index.mjs +456 -0
- package/tools/messaging/message-formatter.mjs +320 -0
- package/tools/messaging/room-manager.mjs +277 -0
- package/tools/messaging/types.mjs +94 -0
- package/tools/providers/pi-bridge-policy.mjs +4 -0
- package/tools/ralph-external/daemon-supervisor.mjs +394 -0
- package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
- package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
- package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
- package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
- package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
- package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
- package/tools/ralph-external/lib/worker-termination.mjs +15 -8
- package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
- package/tools/ralph-external/session-launcher.mjs +7 -7
- package/tools/scripts/resource-preflight.mjs +3 -242
- package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
import YAML from 'yaml';
|
|
5
|
+
import { normalizeResources } from './resource-bounds.mjs';
|
|
6
|
+
import { importImpl } from '../_resolve-impl.mjs';
|
|
7
|
+
import { validateUpdatePolicy } from './update-policy.mjs';
|
|
8
|
+
|
|
9
|
+
const { validateMemoryJobArgs } = await importImpl(import.meta.url, 'housekeeper/daemon-config.js');
|
|
10
|
+
const { resolveSensitiveInput } = await importImpl(import.meta.url, 'auth/sensitive-input.js');
|
|
11
|
+
const { credentialReferenceInput } = await importImpl(import.meta.url, 'mcp/credentials.mjs');
|
|
12
|
+
|
|
13
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
|
|
15
|
+
const DEFAULT_CONFIG = {
|
|
16
|
+
daemon: {
|
|
17
|
+
// 'default' runs the full conversational stack; 'housekeeper' loads only
|
|
18
|
+
// the scheduler/runner/store, watcher/router and minimal IPC (epic #3353).
|
|
19
|
+
profile: 'default',
|
|
20
|
+
heartbeat_interval_seconds: 30,
|
|
21
|
+
max_parallel_actions: 3,
|
|
22
|
+
action_timeout_minutes: 120,
|
|
23
|
+
log: {
|
|
24
|
+
max_size_mb: 50,
|
|
25
|
+
max_files: 5,
|
|
26
|
+
level: 'info'
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
watch: {
|
|
30
|
+
enabled: true,
|
|
31
|
+
paths: [
|
|
32
|
+
{
|
|
33
|
+
path: '.aiwg/',
|
|
34
|
+
events: ['create', 'modify', 'delete'],
|
|
35
|
+
ignore: ['*.tmp', 'working/**', 'daemon/**']
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
path: 'src/',
|
|
39
|
+
events: ['modify'],
|
|
40
|
+
extensions: ['.ts', '.js', '.mjs']
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
path: 'test/',
|
|
44
|
+
events: ['modify'],
|
|
45
|
+
extensions: ['.test.ts', '.test.js']
|
|
46
|
+
}
|
|
47
|
+
],
|
|
48
|
+
debounce_ms: 2000,
|
|
49
|
+
reconcile_interval_ms: 60000,
|
|
50
|
+
polling: false,
|
|
51
|
+
poll_interval_ms: 5000,
|
|
52
|
+
generated_output_paths: ['.aiwg/daemon/']
|
|
53
|
+
},
|
|
54
|
+
webhook: {
|
|
55
|
+
enabled: false,
|
|
56
|
+
port: 9471,
|
|
57
|
+
host: '127.0.0.1',
|
|
58
|
+
secret_env: 'AIWG_WEBHOOK_SECRET',
|
|
59
|
+
endpoints: [
|
|
60
|
+
{ path: '/ci', method: 'POST' },
|
|
61
|
+
{ path: '/health', method: 'GET' }
|
|
62
|
+
]
|
|
63
|
+
},
|
|
64
|
+
schedule: {
|
|
65
|
+
enabled: true,
|
|
66
|
+
jobs: [
|
|
67
|
+
{
|
|
68
|
+
id: 'health-check',
|
|
69
|
+
cron: '0 */6 * * *',
|
|
70
|
+
action: 'doctor'
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
id: 'artifact-audit',
|
|
74
|
+
cron: '0 9 * * 1',
|
|
75
|
+
action: 'validate-metadata'
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
},
|
|
79
|
+
supervisor: {
|
|
80
|
+
max_concurrent: 4,
|
|
81
|
+
max_queue_depth: 20,
|
|
82
|
+
restart_intensity: { max_restarts: 3, window_seconds: 300 },
|
|
83
|
+
circuit_breaker: { failure_threshold: 5, cooldown_ms: 120000 },
|
|
84
|
+
daily_budget_usd: 0,
|
|
85
|
+
behaviors: ['ops-toolset'],
|
|
86
|
+
},
|
|
87
|
+
interface: {
|
|
88
|
+
web: {
|
|
89
|
+
enabled: false,
|
|
90
|
+
port: 7474,
|
|
91
|
+
host: '127.0.0.1',
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
rules: []
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export class Config {
|
|
98
|
+
#recipients = new Map();
|
|
99
|
+
#secretNames = new Set();
|
|
100
|
+
#secretValues = new Set();
|
|
101
|
+
#warnedLiteral = false;
|
|
102
|
+
|
|
103
|
+
constructor(configPath = '.aiwg/daemon.json') {
|
|
104
|
+
this.configPath = configPath;
|
|
105
|
+
this.config = null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
load() {
|
|
109
|
+
// Try YAML first, then JSON, then defaults
|
|
110
|
+
const yamlPath = this.configPath.replace(/\.json$/, '.yaml');
|
|
111
|
+
const ymlPath = this.configPath.replace(/\.json$/, '.yml');
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
if (fs.existsSync(yamlPath)) {
|
|
115
|
+
const content = fs.readFileSync(yamlPath, 'utf8');
|
|
116
|
+
this.config = YAML.parse(content);
|
|
117
|
+
this.configPath = yamlPath;
|
|
118
|
+
} else if (fs.existsSync(ymlPath)) {
|
|
119
|
+
const content = fs.readFileSync(ymlPath, 'utf8');
|
|
120
|
+
this.config = YAML.parse(content);
|
|
121
|
+
this.configPath = ymlPath;
|
|
122
|
+
} else if (fs.existsSync(this.configPath)) {
|
|
123
|
+
const content = fs.readFileSync(this.configPath, 'utf8');
|
|
124
|
+
this.config = JSON.parse(content);
|
|
125
|
+
} else {
|
|
126
|
+
this.config = DEFAULT_CONFIG;
|
|
127
|
+
this.save();
|
|
128
|
+
}
|
|
129
|
+
} catch (error) {
|
|
130
|
+
// Parser errors can quote the input, including literal credentials.
|
|
131
|
+
console.error('Failed to load daemon config; using defaults. Check JSON/YAML syntax.');
|
|
132
|
+
this.config = DEFAULT_CONFIG;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return this.config;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Resolve only active recipients, without replacing references in saved config. Never prompts. */
|
|
139
|
+
async resolveSecrets(dependencies = {}) {
|
|
140
|
+
const environment = dependencies.environment ?? process.env;
|
|
141
|
+
const recipients = new Map();
|
|
142
|
+
this.#secretNames = new Set(['AIWG_WEB_TOKEN', 'AIWG_WEBHOOK_SECRET', 'AIWG_TELEGRAM_TOKEN',
|
|
143
|
+
'AIWG_DISCORD_TOKEN', 'AIWG_SLACK_BOT_TOKEN', 'AIWG_SLACK_WEBHOOK_URL']);
|
|
144
|
+
this.#secretValues.clear();
|
|
145
|
+
const warnLiteral = () => {
|
|
146
|
+
if (this.#warnedLiteral) return;
|
|
147
|
+
this.#warnedLiteral = true;
|
|
148
|
+
(dependencies.warn ?? console.warn)('Warning: daemon config contains literal secrets; use ENV_NAME, file:ABSOLUTE_PATH, or store:NAME references in *_ref fields.');
|
|
149
|
+
};
|
|
150
|
+
for (const [section, fields] of [['interface.web', ['token']], ['messaging.telegram', ['botToken', 'token']],
|
|
151
|
+
['messaging.discord', ['botToken', 'token']], ['messaging.slack', ['botToken', 'webhookUrl']]]) {
|
|
152
|
+
const settings = this.get(section) ?? {};
|
|
153
|
+
for (const field of fields) {
|
|
154
|
+
const value = settings[field];
|
|
155
|
+
const template = typeof value === 'string' && /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(value);
|
|
156
|
+
const reference = settings[`${field}_ref`] ?? template?.[1];
|
|
157
|
+
if (typeof reference === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) this.#secretNames.add(reference);
|
|
158
|
+
if (value && !template && !(typeof value === 'string' && /^(?:file|store):/.test(value))) {
|
|
159
|
+
this.#secretValues.add(value);
|
|
160
|
+
warnLiteral();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const webhookRef = this.get('webhook.secret_env');
|
|
165
|
+
if (typeof webhookRef === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(webhookRef)) this.#secretNames.add(webhookRef);
|
|
166
|
+
const resolve = async (settings, field, legacyEnv, label, aliases = []) => {
|
|
167
|
+
const referenceField = label === 'webhook.secret_env' ? label : `${label}_ref`;
|
|
168
|
+
const fields = [field, ...aliases];
|
|
169
|
+
const refField = fields.find(key => settings[`${key}_ref`] !== undefined);
|
|
170
|
+
const literalField = fields.find(key => settings[key]);
|
|
171
|
+
const literal = literalField ? settings[literalField] : undefined;
|
|
172
|
+
// Existing profile templates use ${NAME}. Explicit *_ref fields avoid
|
|
173
|
+
// guessing whether an ordinary literal token is an environment name.
|
|
174
|
+
const template = typeof literal === 'string' && /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(literal);
|
|
175
|
+
const reference = refField ? settings[`${refField}_ref`]
|
|
176
|
+
: template ? template[1]
|
|
177
|
+
: typeof literal === 'string' && /^(?:file|store):/.test(literal) ? literal : undefined;
|
|
178
|
+
if (refField || reference !== undefined) {
|
|
179
|
+
let source;
|
|
180
|
+
try { source = credentialReferenceInput(reference); }
|
|
181
|
+
catch { throw new Error(`${label}: use ENV_NAME, file:ABSOLUTE_PATH, or store:NAME in ${referenceField}.`); }
|
|
182
|
+
if (source.env) this.#secretNames.add(source.env);
|
|
183
|
+
try {
|
|
184
|
+
const value = await resolveSensitiveInput({ prefix: 'value', ...source }, { ...dependencies, isTTY: false });
|
|
185
|
+
this.#secretValues.add(value);
|
|
186
|
+
return value;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
// Shared resolver diagnostics contain source names/checks, never file/store bytes.
|
|
189
|
+
throw new Error(`${label}: ${error.message} Supply ENV_NAME, file:ABSOLUTE_PATH, or store:NAME via ${referenceField}.`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (literal) {
|
|
193
|
+
warnLiteral();
|
|
194
|
+
this.#secretValues.add(literal);
|
|
195
|
+
return literal;
|
|
196
|
+
}
|
|
197
|
+
// Implicit legacy input stays optional and keeps its original bytes.
|
|
198
|
+
const value = environment[legacyEnv];
|
|
199
|
+
if (value) this.#secretValues.add(value);
|
|
200
|
+
return value;
|
|
201
|
+
};
|
|
202
|
+
if (this.get('daemon.profile') !== 'housekeeper') {
|
|
203
|
+
const web = this.get('interface.web');
|
|
204
|
+
if (web?.enabled) recipients.set('web', { ...web,
|
|
205
|
+
token: await resolve(web, 'token', 'AIWG_WEB_TOKEN', 'interface.web.token') });
|
|
206
|
+
const webhook = this.get('webhook');
|
|
207
|
+
if (webhook?.enabled) {
|
|
208
|
+
// secret_env is the existing reference field; preserve the optional
|
|
209
|
+
// default variable while explicit missing references fail closed.
|
|
210
|
+
const legacyName = webhook.secret_env ?? 'AIWG_WEBHOOK_SECRET';
|
|
211
|
+
const legacyVariable = typeof legacyName === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(legacyName);
|
|
212
|
+
const selected = legacyVariable ? {} : { secret_ref: legacyName };
|
|
213
|
+
recipients.set('webhook', { ...webhook,
|
|
214
|
+
secret: await resolve(selected, 'secret', legacyVariable ? legacyName : 'AIWG_WEBHOOK_SECRET', 'webhook.secret_env') });
|
|
215
|
+
}
|
|
216
|
+
for (const [name, envName] of [['telegram', 'AIWG_TELEGRAM_TOKEN'], ['discord', 'AIWG_DISCORD_TOKEN'],
|
|
217
|
+
['slack', 'AIWG_SLACK_WEBHOOK_URL']]) {
|
|
218
|
+
const settings = this.get(`messaging.${name}`) ?? {};
|
|
219
|
+
if (settings.enabled === false && !environment[envName]) continue;
|
|
220
|
+
// Keep legacy env discovery; a configured credential also enables its recipient.
|
|
221
|
+
const credential = (name === 'slack' ? ['webhookUrl'] : ['botToken', 'token'])
|
|
222
|
+
.some(field => settings[field] || settings[`${field}_ref`] !== undefined);
|
|
223
|
+
if (!credential && !environment[envName]) continue;
|
|
224
|
+
const resolved = { ...settings };
|
|
225
|
+
if (name === 'slack') {
|
|
226
|
+
resolved.webhookUrl = await resolve(settings, 'webhookUrl', envName, 'messaging.slack.webhookUrl');
|
|
227
|
+
resolved.botToken = await resolve(settings, 'botToken', 'AIWG_SLACK_BOT_TOKEN', 'messaging.slack.botToken');
|
|
228
|
+
} else {
|
|
229
|
+
resolved.botToken = await resolve(settings, 'botToken', envName, `messaging.${name}.botToken`, ['token']);
|
|
230
|
+
delete resolved.token;
|
|
231
|
+
}
|
|
232
|
+
recipients.set(name, resolved);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
this.#recipients = recipients;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Each consumer asks for its own config, never the complete resolved secret set. */
|
|
239
|
+
recipientConfig(name) { return this.#recipients.get(name); }
|
|
240
|
+
|
|
241
|
+
/** Preserve worker/provider auth while excluding daemon-only credentials. */
|
|
242
|
+
workerEnvironment(environment = process.env) {
|
|
243
|
+
return Object.fromEntries(Object.entries(environment).filter(([name, value]) =>
|
|
244
|
+
!this.#secretNames.has(name) && !this.#secretValues.has(value)));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
save() {
|
|
248
|
+
try {
|
|
249
|
+
const dir = path.dirname(this.configPath);
|
|
250
|
+
if (!fs.existsSync(dir)) {
|
|
251
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
252
|
+
}
|
|
253
|
+
fs.writeFileSync(this.configPath, JSON.stringify(this.config, null, 2));
|
|
254
|
+
} catch (error) {
|
|
255
|
+
console.error(`Failed to save config to ${this.configPath}:`, error.message);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
validate() {
|
|
260
|
+
const errors = [];
|
|
261
|
+
|
|
262
|
+
if (!this.config.daemon) {
|
|
263
|
+
errors.push('Missing daemon configuration section');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (this.config.daemon?.profile !== undefined
|
|
267
|
+
&& !['default', 'housekeeper'].includes(this.config.daemon.profile)) {
|
|
268
|
+
errors.push('daemon.profile must be "default" or "housekeeper"');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (this.config.watch?.enabled && !Array.isArray(this.config.watch.paths)) {
|
|
272
|
+
errors.push('watch.paths must be an array');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (this.config.watch) {
|
|
276
|
+
const watch = this.config.watch;
|
|
277
|
+
for (const [key, minimum] of [['debounce_ms', 0], ['reconcile_interval_ms', 0], ['poll_interval_ms', 1]]) {
|
|
278
|
+
if (watch[key] !== undefined && (!Number.isFinite(watch[key]) || watch[key] < minimum)) {
|
|
279
|
+
errors.push(`watch.${key} must be a number >= ${minimum}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
for (const [label, settings] of [['watch', watch], ...(Array.isArray(watch.paths)
|
|
283
|
+
? watch.paths.map((root, index) => [`watch.paths[${index}]`, root]) : [])]) {
|
|
284
|
+
if (!settings || typeof settings !== 'object') {
|
|
285
|
+
errors.push(`${label} must be an object`);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (settings.polling !== undefined && typeof settings.polling !== 'boolean') {
|
|
289
|
+
errors.push(`${label}.polling must be a boolean`);
|
|
290
|
+
}
|
|
291
|
+
if (settings.generated_output_paths !== undefined && (!Array.isArray(settings.generated_output_paths) ||
|
|
292
|
+
settings.generated_output_paths.some(output => typeof output !== 'string' || !output))) {
|
|
293
|
+
errors.push(`${label}.generated_output_paths must be an array of non-empty paths`);
|
|
294
|
+
}
|
|
295
|
+
if (label !== 'watch' && (typeof settings.path !== 'string' || !settings.path)) {
|
|
296
|
+
errors.push(`${label}.path must be a non-empty path`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (this.config.webhook?.enabled) {
|
|
302
|
+
if (!this.config.webhook.port || this.config.webhook.port < 1 || this.config.webhook.port > 65535) {
|
|
303
|
+
errors.push('webhook.port must be between 1 and 65535');
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (this.config.schedule?.enabled && !Array.isArray(this.config.schedule.jobs)) {
|
|
308
|
+
errors.push('schedule.jobs must be an array');
|
|
309
|
+
}
|
|
310
|
+
for (const job of Array.isArray(this.config.schedule?.jobs) ? this.config.schedule.jobs : []) {
|
|
311
|
+
if (!job?.kind?.startsWith('memory.')) continue;
|
|
312
|
+
try { validateMemoryJobArgs(job.kind, job.args); }
|
|
313
|
+
catch (error) { errors.push(`schedule job "${job.id}": ${error.message}`); }
|
|
314
|
+
if (job.kind === 'memory.apply') errors.push(...validateUpdatePolicy({ windows: job.args?.windows }));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// B6 resource bounds: validated envelope with safe defaults; the runner
|
|
318
|
+
// and watcher enforce the normalized values (see resource-bounds.mjs).
|
|
319
|
+
if (this.config.resources !== undefined) {
|
|
320
|
+
if (!this.config.resources || typeof this.config.resources !== 'object' || Array.isArray(this.config.resources)) {
|
|
321
|
+
errors.push('resources must be an object');
|
|
322
|
+
} else {
|
|
323
|
+
for (const message of normalizeResources(this.config.resources).errors) errors.push(message);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// The housekeeper profile runs deterministic owner operations only: no
|
|
328
|
+
// prompt-based actions, so no model calls are possible (epic #3353).
|
|
329
|
+
if (this.config.daemon?.profile === 'housekeeper' && Array.isArray(this.config.schedule?.jobs)) {
|
|
330
|
+
for (const job of this.config.schedule.jobs) {
|
|
331
|
+
if (job?.action || job?.prompt) {
|
|
332
|
+
errors.push(`schedule job "${job?.id || '?'}": action/prompt jobs are not allowed in the housekeeper profile`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Validate modes section
|
|
338
|
+
if (this.config.modes?.autonomous?.enabled) {
|
|
339
|
+
if (!Array.isArray(this.config.modes.autonomous.allowed_actions)) {
|
|
340
|
+
errors.push('modes.autonomous.allowed_actions must be an array');
|
|
341
|
+
}
|
|
342
|
+
if (typeof this.config.modes.autonomous.budget_cap_usd !== 'number' || this.config.modes.autonomous.budget_cap_usd < 0) {
|
|
343
|
+
errors.push('modes.autonomous.budget_cap_usd must be a non-negative number');
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Validate messaging rooms
|
|
348
|
+
if (this.config.messaging) {
|
|
349
|
+
for (const [platform, pConfig] of Object.entries(this.config.messaging)) {
|
|
350
|
+
if (pConfig?.rooms && !Array.isArray(pConfig.rooms)) {
|
|
351
|
+
errors.push(`messaging.${platform}.rooms must be an array`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// Validate docker section
|
|
357
|
+
if (this.config.docker?.enabled) {
|
|
358
|
+
if (!this.config.docker.image) {
|
|
359
|
+
errors.push('docker.image is required when docker is enabled');
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return errors;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
get(key) {
|
|
367
|
+
const keys = key.split('.');
|
|
368
|
+
let value = this.config;
|
|
369
|
+
for (const k of keys) {
|
|
370
|
+
if (value === undefined || value === null) return undefined;
|
|
371
|
+
value = value[k];
|
|
372
|
+
}
|
|
373
|
+
return value;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export default Config;
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
const MINUTE = 60_000;
|
|
4
|
+
const DAY = 24 * 60 * MINUTE;
|
|
5
|
+
const formatters = new Map();
|
|
6
|
+
|
|
7
|
+
function wallTime(ms, timezone) {
|
|
8
|
+
if (timezone === 'UTC') {
|
|
9
|
+
const date = new Date(ms);
|
|
10
|
+
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes());
|
|
11
|
+
}
|
|
12
|
+
if (!formatters.has(timezone)) formatters.set(timezone, new Intl.DateTimeFormat('en-CA', {
|
|
13
|
+
timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
14
|
+
hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
|
15
|
+
}));
|
|
16
|
+
const parts = Object.fromEntries(formatters.get(timezone).formatToParts(ms).map(p => [p.type, p.value]));
|
|
17
|
+
return Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour, +parts.minute);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function fieldValues(field, min, max) {
|
|
21
|
+
const values = new Set();
|
|
22
|
+
for (const entry of field.split(',')) {
|
|
23
|
+
const match = /^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/.exec(entry);
|
|
24
|
+
if (!match) throw new Error(`Invalid cron field: ${field}`);
|
|
25
|
+
const step = Number(match[2] || 1);
|
|
26
|
+
const range = match[1] === '*' ? [min, max] : match[1].split('-').map(Number);
|
|
27
|
+
const start = range[0];
|
|
28
|
+
const end = range[1] ?? (match[2] ? max : start);
|
|
29
|
+
if (step < 1 || step > max - min + 1 || start < min || end > max || start > end) throw new Error(`Invalid cron field: ${field}`);
|
|
30
|
+
for (let value = start; value <= end; value += step) values.add(value);
|
|
31
|
+
}
|
|
32
|
+
return values;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseCron(expression) {
|
|
36
|
+
const fields = expression?.trim().split(/\s+/);
|
|
37
|
+
if (fields?.length !== 5) throw new Error('Cron requires five fields');
|
|
38
|
+
return fields.map((field, i) => fieldValues(field, [0, 0, 1, 1, 0][i], [59, 23, 31, 12, 6][i]));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Named-zone civil cron: choose the first fold occurrence; shift gaps forward.
|
|
42
|
+
* Search civil days, not missed UTC slots, so years of downtime cost one next-run lookup.
|
|
43
|
+
* Day-of-month AND day-of-week preserves the daemon's existing convention.
|
|
44
|
+
*/
|
|
45
|
+
export function nextCronRun(expression, after, timezone = 'UTC') {
|
|
46
|
+
const fields = parseCron(expression);
|
|
47
|
+
const afterMs = +new Date(after);
|
|
48
|
+
if (!Number.isFinite(afterMs)) throw new Error('Invalid cron clock');
|
|
49
|
+
const local = new Date(wallTime(afterMs, timezone));
|
|
50
|
+
const firstDay = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate());
|
|
51
|
+
for (let day = firstDay; day < firstDay + 8 * 366 * DAY; day += DAY) {
|
|
52
|
+
const date = new Date(day);
|
|
53
|
+
if (!fields[2].has(date.getUTCDate()) || !fields[3].has(date.getUTCMonth() + 1) || !fields[4].has(date.getUTCDay())) continue;
|
|
54
|
+
const offsets = new Set(timezone === 'UTC' ? [0] : [-36, -12, 12, 36].map(hours => {
|
|
55
|
+
const ms = day + hours * 60 * MINUTE;
|
|
56
|
+
return wallTime(ms, timezone) - ms;
|
|
57
|
+
}));
|
|
58
|
+
let next = Infinity;
|
|
59
|
+
for (const hour of fields[1]) for (const minute of fields[0]) {
|
|
60
|
+
const target = day + (hour * 60 + minute) * MINUTE;
|
|
61
|
+
const candidates = [...offsets].map(offset => target - offset);
|
|
62
|
+
const exact = candidates.filter(ms => wallTime(ms, timezone) === target);
|
|
63
|
+
// Missing time: compatible shift by the transition gap (02:30 -> 03:30).
|
|
64
|
+
const shifted = candidates.filter(ms => wallTime(ms, timezone) > target)
|
|
65
|
+
.sort((a, b) => wallTime(a, timezone) - wallTime(b, timezone));
|
|
66
|
+
const instant = exact.length ? Math.min(...exact) : shifted[0];
|
|
67
|
+
if (instant > afterMs) next = Math.min(next, instant);
|
|
68
|
+
}
|
|
69
|
+
if (Number.isFinite(next)) return new Date(next);
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`Cron has no occurrence within eight years: ${expression}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class CronScheduler extends EventEmitter {
|
|
75
|
+
constructor(config, { taskStore = null, now = Date.now } = {}) {
|
|
76
|
+
super();
|
|
77
|
+
this.config = config;
|
|
78
|
+
this.taskStore = taskStore;
|
|
79
|
+
this.now = now;
|
|
80
|
+
this.intervals = new Map();
|
|
81
|
+
this.lastFires = new Map();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
start() {
|
|
85
|
+
if (!this.config.enabled) return;
|
|
86
|
+
for (const job of this.config.jobs) this.scheduleJob(job);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
scheduleJob(job) {
|
|
90
|
+
if (this.intervals.has(job.id)) return;
|
|
91
|
+
const expression = job.cron || job.schedule;
|
|
92
|
+
// Reviewed one-shot memory plans are run manually, never given a timer.
|
|
93
|
+
if (!expression && job.kind === 'memory.apply') return;
|
|
94
|
+
parseCron(expression);
|
|
95
|
+
if (job.kind && job.kind !== 'agent.prompt') {
|
|
96
|
+
if (!this.taskStore) throw new Error('Typed schedules require a TaskStore');
|
|
97
|
+
this.taskStore.ensureSchedule(job, nextCronRun(expression, this.now(), job.timezone).toISOString());
|
|
98
|
+
this.tick(job);
|
|
99
|
+
}
|
|
100
|
+
const interval = setInterval(() => {
|
|
101
|
+
try { this.tick(job); }
|
|
102
|
+
catch (error) {
|
|
103
|
+
// Stop only this trigger. Persisted intent is retained; never continue blind.
|
|
104
|
+
clearInterval(this.intervals.get(job.id));
|
|
105
|
+
this.intervals.delete(job.id);
|
|
106
|
+
this.emit('recovery-required', { jobId: job.id, error });
|
|
107
|
+
}
|
|
108
|
+
}, job.kind && job.kind !== 'agent.prompt' ? 1000 : MINUTE);
|
|
109
|
+
this.intervals.set(job.id, interval);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Public tick for deterministic tests and a single bounded downtime reconciliation. */
|
|
113
|
+
tick(job) {
|
|
114
|
+
const now = this.now();
|
|
115
|
+
if (!job.kind || job.kind === 'agent.prompt') {
|
|
116
|
+
const date = new Date(now);
|
|
117
|
+
if (!this.cronMatches(job.cron, date, job.timezone)) return;
|
|
118
|
+
const minute = Math.floor(now / MINUTE);
|
|
119
|
+
if (Math.floor(+(this.lastFires.get(job.id) || 0) / MINUTE) === minute) return;
|
|
120
|
+
this.lastFires.set(job.id, date);
|
|
121
|
+
this.emit('event', { source: 'schedule', type: 'cron.fired',
|
|
122
|
+
payload: { job_id: job.id, action: job.action, ...(job.prompt ? { prompt: job.prompt } : {}) } });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
let fireTime = null;
|
|
126
|
+
const record = this.taskStore.changeSchedule(job.id, record => {
|
|
127
|
+
if (!record) throw new Error(`Schedule missing: ${job.id}`);
|
|
128
|
+
if (record.state === 'blocked' || record.state === 'running') return record;
|
|
129
|
+
if (record.state === 'retry' || record.state === 'pending') {
|
|
130
|
+
if (!record.retryAt || Date.parse(record.retryAt) <= now) fireTime = record.pendingFireTime;
|
|
131
|
+
return record;
|
|
132
|
+
}
|
|
133
|
+
if (Date.parse(record.nextRun) > now) return record;
|
|
134
|
+
const missed = Date.parse(record.nextRun) < Math.floor(now / MINUTE) * MINUTE;
|
|
135
|
+
const due = record.nextRun;
|
|
136
|
+
record.nextRun = nextCronRun(job.cron || job.schedule, now, record.timezone).toISOString();
|
|
137
|
+
if (missed && record.missedRunPolicy === 'skip') {
|
|
138
|
+
const timestamp = new Date(now).toISOString();
|
|
139
|
+
record.lastReceipt = { jobId: job.id, fireTime: due, state: 'skipped',
|
|
140
|
+
reason: 'missed-run', summary: 'Missed slots coalesced and skipped', exitStatus: null,
|
|
141
|
+
startedAt: timestamp, finishedAt: timestamp, durationMs: 0, attemptCount: 0 };
|
|
142
|
+
record.receipts.push(record.lastReceipt);
|
|
143
|
+
} else {
|
|
144
|
+
record.state = 'pending';
|
|
145
|
+
record.pendingFireTime = due;
|
|
146
|
+
record.attemptCount = 0;
|
|
147
|
+
fireTime = due;
|
|
148
|
+
}
|
|
149
|
+
return record;
|
|
150
|
+
});
|
|
151
|
+
if (fireTime) {
|
|
152
|
+
this.lastFires.set(job.id, new Date(fireTime));
|
|
153
|
+
this.emit('event', { source: 'schedule', type: 'cron.fired',
|
|
154
|
+
payload: { ...record.job, job_id: job.id, fireTime } });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
cronMatches(expression, date, timezone = 'UTC') {
|
|
159
|
+
const fields = parseCron(expression);
|
|
160
|
+
const local = new Date(wallTime(+date, timezone));
|
|
161
|
+
return [local.getUTCMinutes(), local.getUTCHours(), local.getUTCDate(), local.getUTCMonth() + 1, local.getUTCDay()]
|
|
162
|
+
.every((value, i) => fields[i].has(value));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
matchesField(field, value, min, max) { return fieldValues(field, min, max).has(value); }
|
|
166
|
+
|
|
167
|
+
stop() {
|
|
168
|
+
for (const interval of this.intervals.values()) clearInterval(interval);
|
|
169
|
+
this.intervals.clear();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
getStats() {
|
|
173
|
+
return { enabled: this.config.enabled, jobs: this.config.jobs.length,
|
|
174
|
+
last_fires: Object.fromEntries([...this.lastFires].map(([id, date]) => [id, date.toISOString()])) };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export default CronScheduler;
|