-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
489 lines (437 loc) · 19.8 KB
/
index.ts
File metadata and controls
489 lines (437 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { execFileSync } from "node:child_process";
import { homedir } from "node:os";
import { join } from "node:path";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { registerLinearProvider } from "./src/api/auth.js";
import { registerCli } from "./src/infra/cli.js";
import { createLinearTools } from "./src/tools/tools.js";
import { handleLinearWebhook } from "./src/pipeline/webhook.js";
import { handleOAuthCallback } from "./src/api/oauth-callback.js";
import { LinearAgentApi, resolveLinearToken } from "./src/api/linear-api.js";
import { createDispatchService } from "./src/pipeline/dispatch-service.js";
import { registerDispatchMethods } from "./src/gateway/dispatch-methods.js";
import { readDispatchState, lookupSessionMapping, getActiveDispatch, transitionDispatch, type DispatchStatus } from "./src/pipeline/dispatch-state.js";
import { triggerAudit, processVerdict, type HookContext } from "./src/pipeline/pipeline.js";
import { markFlowTerminal } from "./src/pipeline/taskflow-bridge.js";
import { createNotifierFromConfig, type NotifyFn } from "./src/infra/notify.js";
import { readPlanningState, setPlanningCache } from "./src/pipeline/planning-state.js";
import { createPlannerTools } from "./src/tools/planner-tools.js";
import { registerDispatchCommands } from "./src/infra/commands.js";
import { createDispatchHistoryTool } from "./src/tools/dispatch-history-tool.js";
import { readDispatchState as readStateForHook, listActiveDispatches as listActiveForHook } from "./src/pipeline/dispatch-state.js";
import { startTokenRefreshTimer, stopTokenRefreshTimer } from "./src/infra/token-refresh-timer.js";
const SUCCESS_STATUSES = new Set(["ok", "success", "completed", "complete", "done", "pass", "passed"]);
const FAILURE_STATUSES = new Set(["error", "failed", "failure", "timeout", "timed_out", "cancelled", "canceled", "aborted", "unknown"]);
function parseCompletionSuccess(event: any): boolean {
if (typeof event?.success === "boolean") {
return event.success;
}
const status = typeof event?.status === "string" ? event.status.trim().toLowerCase() : "";
if (status) {
if (SUCCESS_STATUSES.has(status)) return true;
if (FAILURE_STATUSES.has(status)) return false;
}
if (typeof event?.error === "string" && event.error.trim().length > 0) {
return false;
}
return true;
}
function extractCompletionOutput(event: any): string {
if (typeof event?.output === "string" && event.output.trim().length > 0) {
return event.output;
}
if (typeof event?.result === "string" && event.result.trim().length > 0) {
return event.result;
}
const assistantBlocks = (event?.messages ?? [])
.filter((m: any) => m?.role === "assistant")
.flatMap((m: any) => {
if (typeof m?.content === "string") {
return [m.content];
}
if (Array.isArray(m?.content)) {
return m.content
.filter((b: any) => b?.type === "text" && typeof b?.text === "string")
.map((b: any) => b.text);
}
return [];
})
.filter((value: string) => value.trim().length > 0);
return assistantBlocks.join("\n");
}
export default function register(api: OpenClawPluginApi) {
const pluginConfig = api.pluginConfig;
// Check token availability (config → env → auth profile store)
const tokenInfo = resolveLinearToken(pluginConfig);
if (!tokenInfo.accessToken) {
api.logger.warn(
"Linear: no access token found. Options: (1) run OAuth flow, (2) set LINEAR_ACCESS_TOKEN env var, " +
"(3) add accessToken to plugin config. Agent pipeline will not function without it.",
);
}
// Register Linear as an auth provider (OAuth flow with agent scopes)
registerLinearProvider(api);
// Register CLI commands: openclaw openclaw-linear auth|status
api.registerCli(({ program }) => registerCli(program as any, api), {
commands: ["openclaw-linear"],
});
// Register Linear tools for the agent
api.registerTool((ctx) => {
return createLinearTools(api, ctx);
});
// Register planner tools (context injected at runtime via setActivePlannerContext)
api.registerTool(() => createPlannerTools());
// Register dispatch_history tool for agent context
api.registerTool(() => createDispatchHistoryTool(api, pluginConfig));
// Register zero-LLM slash commands for dispatch ops
registerDispatchCommands(api);
// Register Linear webhook handler on a dedicated route
api.registerHttpRoute({
path: "/linear/webhook",
auth: "plugin",
match: "exact",
handler: async (req, res) => {
await handleLinearWebhook(api, req, res);
},
});
// Back-compat route so existing production webhook URLs keep working.
api.registerHttpRoute({
path: "/hooks/linear",
auth: "plugin",
match: "exact",
handler: async (req, res) => {
await handleLinearWebhook(api, req, res);
},
});
// Register OAuth callback route
api.registerHttpRoute({
path: "/linear/oauth/callback",
auth: "plugin",
match: "exact",
handler: async (req, res) => {
await handleOAuthCallback(api, req, res);
},
});
// Register dispatch monitor service (stale detection, session hydration, cleanup)
api.registerService(createDispatchService(api));
// Register dispatch gateway RPC methods (list, get, retry, escalate, cancel, stats)
registerDispatchMethods(api);
// Hydrate planning state on startup
readPlanningState(pluginConfig?.planningStatePath as string | undefined).then((state) => {
for (const session of Object.values(state.sessions)) {
if (session.status === "interviewing" || session.status === "plan_review") {
setPlanningCache(session);
api.logger.info(`Planning: restored session for ${session.projectName} (${session.rootIdentifier})`);
}
}
}).catch((err) => api.logger.warn(`Planning state hydration failed: ${err}`));
// ---------------------------------------------------------------------------
// Dispatch pipeline v2: notifier + completion lifecycle hooks
// ---------------------------------------------------------------------------
// Instantiate notifier (Discord, Slack, or both — config-driven)
const notify: NotifyFn = createNotifierFromConfig(pluginConfig, api.runtime, api);
// ---------------------------------------------------------------------------
// Typed dispatch completion handler (shared by agent_end + subagent_ended)
// ---------------------------------------------------------------------------
const handleDispatchCompletion = async (
sessionKey: string,
success: boolean,
output: string,
hookName: string,
) => {
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readDispatchState(statePath);
const mapping = lookupSessionMapping(state, sessionKey);
if (!mapping) return; // Not a dispatch sub-agent
const dispatch = getActiveDispatch(state, mapping.dispatchId);
if (!dispatch) {
api.logger.info(`${hookName}: dispatch ${mapping.dispatchId} no longer active`);
return;
}
// Stale event rejection — only process if attempt matches
if (dispatch.attempt !== mapping.attempt) {
api.logger.info(
`${hookName}: stale event for ${mapping.dispatchId} ` +
`(event attempt=${mapping.attempt}, current=${dispatch.attempt})`
);
return;
}
// Create Linear API for hook context
const tokenInfo = resolveLinearToken(pluginConfig);
if (!tokenInfo.accessToken) {
api.logger.error(`${hookName}: no Linear access token — cannot process dispatch event`);
return;
}
const linearApi = new LinearAgentApi(tokenInfo.accessToken, {
refreshToken: tokenInfo.refreshToken,
expiresAt: tokenInfo.expiresAt,
});
const hookCtx: HookContext = {
api,
linearApi,
notify,
pluginConfig,
configPath: statePath,
};
if (mapping.phase === "worker") {
api.logger.info(`${hookName}: worker completed for ${mapping.dispatchId} - triggering audit`);
await triggerAudit(hookCtx, dispatch, { success, output }, sessionKey);
} else if (mapping.phase === "audit") {
api.logger.info(`${hookName}: audit completed for ${mapping.dispatchId} - processing verdict`);
await processVerdict(hookCtx, dispatch, { success, output }, sessionKey);
}
};
const escalateDispatchError = async (sessionKey: string, err: unknown, hookName: string) => {
try {
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readDispatchState(statePath);
const mapping = sessionKey ? lookupSessionMapping(state, sessionKey) : null;
if (mapping) {
const dispatch = getActiveDispatch(state, mapping.dispatchId);
if (dispatch && dispatch.status !== "done" && dispatch.status !== "stuck" && dispatch.status !== "failed") {
const stuckReason = `Hook error: ${err instanceof Error ? err.message : String(err)}`.slice(0, 500);
await transitionDispatch(
mapping.dispatchId,
dispatch.status as DispatchStatus,
"stuck",
{ stuckReason },
statePath,
);
// Mirror the hook-error escalation into the openclaw task-flow
// registry so the managed flow doesn't sit in "running" forever.
markFlowTerminal(api, dispatch, "failed", stuckReason);
await notify("escalation", {
identifier: dispatch.issueIdentifier,
title: dispatch.issueTitle ?? "Unknown",
status: "stuck",
reason: `Dispatch failed in ${mapping.phase} phase: ${stuckReason}`,
}).catch(() => {});
}
}
} catch (escalateErr) {
api.logger.error(`${hookName} escalation also failed: ${escalateErr}`);
}
};
// agent_end — fires when an agent run completes (primary dispatch handler)
api.on("agent_end", async (event, ctx) => {
const sessionKey = ctx?.sessionKey ?? "";
if (!sessionKey) return;
try {
const output = extractCompletionOutput(event);
const success = parseCompletionSuccess(event);
await handleDispatchCompletion(sessionKey, success, output, "agent_end");
} catch (err) {
api.logger.error(`agent_end hook error: ${err}`);
await escalateDispatchError(sessionKey, err, "agent_end");
}
});
// subagent_ended — fires when a subagent session ends (proper lifecycle hook, new in 3.7)
// This catches sessions_spawn sub-agents with structured outcome data.
api.on("subagent_ended", async (event, ctx) => {
const sessionKey = event.targetSessionKey ?? ctx?.childSessionKey ?? "";
if (!sessionKey) return;
try {
const success = event.outcome === "ok";
const output = event.error ?? event.reason ?? "";
await handleDispatchCompletion(sessionKey, success, output, "subagent_ended");
} catch (err) {
api.logger.error(`subagent_ended hook error: ${err}`);
await escalateDispatchError(sessionKey, err, "subagent_ended");
}
});
// session_start — track dispatch session lifecycle
api.on("session_start", async (event, ctx) => {
const sessionKey = ctx?.sessionKey ?? event?.sessionKey ?? "";
if (!sessionKey) return;
try {
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readDispatchState(statePath);
const mapping = lookupSessionMapping(state, sessionKey);
if (mapping) {
api.logger.info(`session_start: dispatch ${mapping.dispatchId} phase=${mapping.phase} session started`);
}
} catch {
// Never block session start for telemetry
}
});
// session_end — log dispatch session duration for observability
api.on("session_end", async (event, ctx) => {
const sessionKey = ctx?.sessionKey ?? event?.sessionKey ?? "";
if (!sessionKey) return;
try {
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readDispatchState(statePath);
const mapping = lookupSessionMapping(state, sessionKey);
if (mapping) {
const durationSec = event.durationMs ? Math.round(event.durationMs / 1000) : "?";
api.logger.info(
`session_end: dispatch ${mapping.dispatchId} phase=${mapping.phase} ` +
`messages=${event.messageCount} duration=${durationSec}s`
);
}
} catch {
// Never block session end for telemetry
}
});
// after_compaction — log when dispatch sessions compact (visibility into context pressure)
api.on("after_compaction", async (event, ctx) => {
const sessionKey = ctx?.sessionKey ?? "";
if (!sessionKey) return;
try {
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readDispatchState(statePath);
const mapping = lookupSessionMapping(state, sessionKey);
if (mapping) {
api.logger.warn(
`after_compaction: dispatch ${mapping.dispatchId} phase=${mapping.phase} ` +
`compacted ${event.compactedCount} messages (${event.messageCount} remaining)`
);
}
} catch {
// Never block compaction pipeline
}
});
// before_reset — clean up dispatch tracking when a session is reset
api.on("before_reset", async (event, ctx) => {
const sessionKey = ctx?.sessionKey ?? "";
if (!sessionKey) return;
try {
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readDispatchState(statePath);
const mapping = lookupSessionMapping(state, sessionKey);
if (mapping) {
api.logger.warn(
`before_reset: dispatch ${mapping.dispatchId} phase=${mapping.phase} session reset ` +
`(reason: ${event.reason ?? "unknown"})`
);
}
} catch {
// Never block reset
}
});
api.logger.info("Dispatch lifecycle hooks registered: agent_end, subagent_ended, session_start, session_end, after_compaction, before_reset");
// Inject recent dispatch history as context for worker/audit agents
api.on("before_agent_start", async (event: any, ctx: any) => {
try {
const sessionKey = ctx?.sessionKey ?? "";
if (!sessionKey.startsWith("linear-worker-") && !sessionKey.startsWith("linear-audit-")) return;
const statePath = pluginConfig?.dispatchStatePath as string | undefined;
const state = await readStateForHook(statePath);
const active = listActiveForHook(state);
// Include up to 3 recent active dispatches as context
const recent = active.slice(0, 3);
if (recent.length === 0) return;
const lines = recent.map(d =>
`- **${d.issueIdentifier}** (${d.tier}): ${d.status}, attempt ${d.attempt}`
);
return {
prependContext: `<dispatch-history>\nActive dispatches:\n${lines.join("\n")}\n</dispatch-history>\n\n`,
};
} catch {
// Never block agent start for telemetry
}
});
// Hard gate: prepend planning-only constraints to code_run when issue is not "started".
// Even if the orchestrator LLM ignores scope rules, the coding agent receives hard constraints.
api.on("before_tool_call", async (event: any, _ctx: any) => {
if (event.toolName !== "code_run") return;
const { getCurrentSession } = await import("./src/pipeline/active-session.js");
const session = getCurrentSession();
if (!session?.issueId) return; // Non-Linear context, allow
// Check issue state
const hookTokenInfo = resolveLinearToken(pluginConfig);
if (!hookTokenInfo.accessToken) return;
const hookLinearApi = new LinearAgentApi(hookTokenInfo.accessToken, {
refreshToken: hookTokenInfo.refreshToken,
expiresAt: hookTokenInfo.expiresAt,
});
try {
const issue = await hookLinearApi.getIssueDetails(session.issueId);
const stateType = issue?.state?.type ?? "";
const isStarted = stateType === "started";
if (!isStarted) {
const constraint = [
"CRITICAL CONSTRAINT — PLANNING MODE ONLY:",
`This issue (${session.issueIdentifier}) is in "${issue?.state?.name ?? stateType}" state — NOT In Progress.`,
"You may ONLY:",
"- Read and explore files to understand the codebase",
"- Write plan files (PLAN.md, notes, design outlines)",
"- Search code to inform planning",
"You MUST NOT:",
"- Create, modify, or delete source code, config, or infrastructure files",
"- Run system commands that change state (deploys, installs, migrations)",
"- Make external API requests that modify data",
"- Build, implement, or scaffold any application code",
"Plan and explore ONLY. Do not implement anything.",
"---",
].join("\n");
const originalPrompt = event.params?.prompt ?? "";
return {
params: { ...event.params, prompt: `${constraint}\n${originalPrompt}` },
};
}
} catch (err) {
api.logger.warn(`before_tool_call: issue state check failed: ${err}`);
// Don't block on failure — fall through to allow
}
});
// Narration Guard: catch short "Let me explore..." responses that narrate intent
// without actually calling tools, and append a warning for the user.
const NARRATION_PATTERNS = [
/let me (explore|look|investigate|check|dig|analyze|search|find|review|examine)/i,
/i('ll| will) (explore|look into|investigate|check|dig into|analyze|search|find|review)/i,
/let me (take a look|dive into|pull up|go through)/i,
];
const MAX_SHORT_RESPONSE = 250;
api.on("message_sending", (event) => {
const text = event?.content ?? "";
if (!text || text.length > MAX_SHORT_RESPONSE) return;
const isNarration = NARRATION_PATTERNS.some((p) => p.test(text));
if (!isNarration) return;
api.logger.warn(`Narration guard triggered: "${text.slice(0, 80)}..."`);
return {
content:
text +
"\n\n⚠️ _Agent acknowledged but may not have completed the task. Try asking again or rephrase your request._",
};
});
// Check CLI availability (Codex, Claude, Gemini)
const cliChecks: Record<string, string> = {};
const defaultBinDir = join(process.env.HOME ?? homedir(), ".npm-global", "bin");
const cliBins: [string, string, string][] = [
["codex", pluginConfig?.codexBin as string ?? join(defaultBinDir, "codex"), "npm install -g @openai/codex"],
["claude", pluginConfig?.claudeBin as string ?? join(defaultBinDir, "claude"), "npm install -g @anthropic-ai/claude-code"],
["gemini", pluginConfig?.geminiBin as string ?? join(defaultBinDir, "gemini"), "npm install -g @anthropic-ai/gemini-cli"],
];
for (const [name, bin, installCmd] of cliBins) {
try {
const raw = execFileSync(bin, ["--version"], {
encoding: "utf8",
timeout: 15_000,
env: { ...process.env, CLAUDECODE: undefined } as any,
}).trim();
cliChecks[name] = raw || "unknown";
} catch {
// Fallback: check if the file exists (execFileSync can fail in worker contexts)
try {
require("node:fs").accessSync(bin, require("node:fs").constants.X_OK);
cliChecks[name] = "installed (version check skipped)";
} catch {
cliChecks[name] = "not found";
api.logger.warn(
`${name} CLI not found at ${bin}. The ${name}_run tool will fail. Install with: ${installCmd}`,
);
}
}
}
const agentId = (pluginConfig?.defaultAgentId as string) ?? "default";
const orchestration = pluginConfig?.enableOrchestration !== false ? "enabled" : "disabled";
const cliSummary = Object.entries(cliChecks).map(([k, v]) => `${k}: ${v}`).join(", ");
api.logger.info(
`Linear agent extension registered (agent: ${agentId}, token: ${tokenInfo.source !== "none" ? `${tokenInfo.source}` : "missing"}, ${cliSummary}, orchestration: ${orchestration})`,
);
// Start proactive token refresh timer (runs immediately, then every 6h)
startTokenRefreshTimer(api, pluginConfig);
// Clean up timer on process exit
process.on("beforeExit", () => stopTokenRefreshTimer());
}