@justjoshn/pi-pstack 0.15.36-pi.1 → 0.15.36-pi.11
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/CHANGELOG.md +79 -0
- package/README.md +26 -21
- package/agents/ci-watcher.md +28 -0
- package/agents/thermo-nuclear-code-quality-review.md +23 -0
- package/assets/logo.png +0 -0
- package/automations/benny/FOR_AGENTS.md +2 -1
- package/automations/benny/README.md +2 -2
- package/automations/benny/skills/setup-benny/SKILL.md +10 -9
- package/automations/benny/templates/reproduce-automation-prompt.md +1 -1
- package/automations/benny/templates/triage-automation-prompt.md +1 -1
- package/bin/pstack-routines-supervisor +9 -0
- package/docs/guide/01-setup.md +2 -2
- package/docs/guide/07-overnight.md +1 -1
- package/docs/guide/09-make-it-yours.md +1 -1
- package/docs/guide/10-recipes-and-pitfalls.md +1 -1
- package/docs/native-gaps.md +14 -8
- package/docs/parity-reverse-engineering.md +94 -0
- package/docs/parity-status.md +113 -0
- package/package.json +41 -6
- package/packaging/install-supervisor-unit.sh +164 -0
- package/packaging/launchd/com.pstack.routines-supervisor.plist.example +24 -0
- package/packaging/systemd/pstack-routines-supervisor.service.example +15 -0
- package/skills/architect/SKILL.md +1 -1
- package/skills/architect/references/runner-prompt.md +1 -1
- package/skills/arena/SKILL.md +4 -4
- package/skills/check-compiler-errors/SKILL.md +23 -0
- package/skills/create-skill/SKILL.md +515 -29
- package/skills/fix-ci/SKILL.md +29 -0
- package/skills/fix-merge-conflicts/SKILL.md +32 -0
- package/skills/get-pr-comments/SKILL.md +23 -0
- package/skills/how/SKILL.md +1 -1
- package/skills/ketchup/SKILL.md +2 -2
- package/skills/ketchup-video/SKILL.md +2 -2
- package/skills/loop-on-ci/SKILL.md +50 -0
- package/skills/make-bot-ui/SKILL.md +2 -2
- package/skills/make-pr-easy-to-review/SKILL.md +59 -0
- package/skills/new-branch-and-pr/SKILL.md +29 -0
- package/skills/no-inline-imports/SKILL.md +12 -0
- package/skills/poteto-help/SKILL.md +4 -4
- package/skills/poteto-mode/SKILL.md +2 -2
- package/skills/poteto-mode/playbooks/bug-fix.md +1 -1
- package/skills/poteto-mode/playbooks/feature.md +1 -1
- package/skills/poteto-mode/playbooks/hillclimb.md +1 -1
- package/skills/poteto-mode/playbooks/multi-phase-plan.md +2 -2
- package/skills/poteto-mode/playbooks/orchestrate.md +2 -2
- package/skills/poteto-mode/playbooks/perf-issue.md +1 -1
- package/skills/poteto-mode/playbooks/refactoring.md +1 -1
- package/skills/pr-review-canvas/SKILL.md +176 -0
- package/skills/pr-review-canvas/renderer.js +170 -0
- package/skills/pr-review-canvas/styles.css +96 -0
- package/skills/pr-review-canvas/template.html +18 -0
- package/skills/reflect/SKILL.md +2 -2
- package/skills/review-and-ship/SKILL.md +41 -0
- package/skills/run-smoke-tests/SKILL.md +42 -0
- package/skills/setup-pstack/SKILL.md +13 -13
- package/skills/statechart/scripts/test/cli.test.ts +1 -1
- package/skills/swarm/SKILL.md +2 -2
- package/skills/thermo-nuclear-code-quality-review/SKILL.md +192 -0
- package/skills/typescript-exhaustive-switch/SKILL.md +10 -0
- package/skills/verify-this/SKILL.md +74 -0
- package/skills/weekly-review/SKILL.md +32 -0
- package/skills/what-did-i-get-done/SKILL.md +31 -0
- package/skills/why/SKILL.md +2 -2
- package/skills/workflow-from-chats/SKILL.md +50 -0
- package/src/child-env.ts +15 -2
- package/src/index.ts +18 -3
- package/src/loop.ts +63 -14
- package/src/mode.ts +31 -7
- package/src/path-skills.ts +104 -0
- package/src/paths.ts +18 -0
- package/src/pi-command.ts +12 -0
- package/src/plan.ts +109 -24
- package/src/rule.ts +4 -4
- package/src/sections.ts +21 -2
- package/src/subscriptions/durable-store.ts +531 -0
- package/src/subscriptions/durable-types.ts +69 -0
- package/src/subscriptions/ensure-supervisor.ts +67 -0
- package/src/subscriptions/index.ts +310 -282
- package/src/subscriptions/supervisor-main.ts +134 -0
- package/src/subscriptions/supervisor.ts +325 -0
- package/src/subscriptions/webhook.ts +82 -21
- package/src/task/card.ts +29 -0
- package/src/task/models.ts +7 -0
- package/src/task/progress.ts +112 -0
- package/src/task/records.ts +7 -9
- package/src/task/registry.ts +7 -3
- package/src/task/runner.ts +112 -23
- package/src/task/tool.ts +112 -43
- package/src/task/worktree.ts +5 -3
- package/src/todo.ts +8 -3
- package/scripts/live-e2e.mjs +0 -257
- package/test/aliases.test.ts +0 -57
- package/test/ask.test.ts +0 -85
- package/test/autocomplete.test.ts +0 -39
- package/test/e2e/aliases.e2e.test.ts +0 -81
- package/test/e2e/ask.e2e.test.ts +0 -135
- package/test/e2e/harness.ts +0 -179
- package/test/e2e/host.e2e.test.ts +0 -193
- package/test/e2e/lifecycle.e2e.test.ts +0 -99
- package/test/e2e/mode.e2e.test.ts +0 -160
- package/test/e2e/package.e2e.test.ts +0 -67
- package/test/e2e/task.e2e.test.ts +0 -734
- package/test/e2e/todo.e2e.test.ts +0 -59
- package/test/fixtures/cursor-askquestion-calls.json +0 -806
- package/test/fixtures/fake-pi.mjs +0 -96
- package/test/fixtures/image-model.ts +0 -16
- package/test/fixtures/list-models.ts +0 -15
- package/test/fixtures/readonly-shell-exit.ts +0 -17
- package/test/fixtures/scripted-model.ts +0 -113
- package/test/loop.test.ts +0 -209
- package/test/mode.test.ts +0 -143
- package/test/plan.test.ts +0 -126
- package/test/readonly-shell-security.test.ts +0 -84
- package/test/readonly-shell.test.ts +0 -44
- package/test/records.test.ts +0 -143
- package/test/registry.test.ts +0 -18
- package/test/resources.test.ts +0 -162
- package/test/rule.test.ts +0 -92
- package/test/scripts.test.ts +0 -182
- package/test/sections.test.ts +0 -56
- package/test/subscriptions-cron.test.ts +0 -60
- package/test/subscriptions.test.ts +0 -598
- package/test/task-agents.test.ts +0 -49
- package/test/task-card.test.ts +0 -34
- package/test/task-fork.test.ts +0 -233
- package/test/task-format.test.ts +0 -65
- package/test/task-model.test.ts +0 -141
- package/test/task-runner.test.ts +0 -259
- package/test/task-schema.test.ts +0 -50
- package/test/task-status.test.ts +0 -155
- package/test/task-worktree.test.ts +0 -106
- package/test/todo.test.ts +0 -74
- package/test/visualize.test.ts +0 -152
- package/tsconfig.json +0 -5
- package/vitest.config.ts +0 -16
|
@@ -1,14 +1,34 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
|
|
3
|
-
import { StringEnum } from '@earendil-works/pi-ai';
|
|
4
3
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
4
|
+
import { Text } from '@earendil-works/pi-tui';
|
|
5
5
|
import { type Static, Type } from 'typebox';
|
|
6
6
|
import { Value } from 'typebox/value';
|
|
7
7
|
import { isOneShot } from '../modes.ts';
|
|
8
8
|
import { routinesDir } from '../paths.ts';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
|
|
9
|
+
import { parseCron } from './cron.ts';
|
|
10
|
+
import {
|
|
11
|
+
acquireLease,
|
|
12
|
+
cancelDesired,
|
|
13
|
+
canonicalPath,
|
|
14
|
+
createDesired,
|
|
15
|
+
deliverOwner,
|
|
16
|
+
finishFresh,
|
|
17
|
+
isDesired,
|
|
18
|
+
isSupervisorLive,
|
|
19
|
+
type Lease,
|
|
20
|
+
ownerLockPath,
|
|
21
|
+
readArm,
|
|
22
|
+
readRegistry,
|
|
23
|
+
runsDetached,
|
|
24
|
+
startFresh,
|
|
25
|
+
visibleSubscriptions,
|
|
26
|
+
} from './durable-store.ts';
|
|
27
|
+
import type { StoredSubscription } from './durable-types.ts';
|
|
28
|
+
import { defaultEnsureSupervisor, waitForArm, waitForSupervisor } from './ensure-supervisor.ts';
|
|
29
|
+
import { type GhRunner, targetText } from './github.ts';
|
|
30
|
+
import { createSupervisor, type FreshMeta, type Supervisor } from './supervisor.ts';
|
|
31
|
+
import { credentialFile, routineSlug } from './webhook.ts';
|
|
12
32
|
|
|
13
33
|
export const SUBSCRIPTIONS_ENTRY = 'pstack/subscriptions';
|
|
14
34
|
export const WAKE_TYPE = 'pstack/subscription';
|
|
@@ -16,9 +36,6 @@ export const WAKE_TYPE = 'pstack/subscription';
|
|
|
16
36
|
const HOUR_MS = 3_600_000;
|
|
17
37
|
const DEFAULT_EXPIRY_MS = 7 * 24 * HOUR_MS;
|
|
18
38
|
const MAX_EXPIRY_HOURS = 30 * 24;
|
|
19
|
-
// setTimeout fires at once past 2^31-1 ms, so long waits are chained in steps of at most this.
|
|
20
|
-
const MAX_STEP_MS = 24 * 24 * HOUR_MS;
|
|
21
|
-
const MINUTE_MS = 60_000;
|
|
22
39
|
|
|
23
40
|
const TargetSchema = Type.Union([
|
|
24
41
|
Type.Object({ scope: Type.Literal('pr'), prUrl: Type.String() }),
|
|
@@ -28,41 +45,48 @@ const TargetSchema = Type.Union([
|
|
|
28
45
|
const StrategySchema = Type.Union([Type.Literal('wake_self'), Type.Literal('new_session')]);
|
|
29
46
|
const ConfigSchema = Type.Union([
|
|
30
47
|
Type.Object({ kind: Type.Literal('github'), target: TargetSchema }),
|
|
31
|
-
Type.Object({
|
|
32
|
-
|
|
48
|
+
Type.Object({
|
|
49
|
+
kind: Type.Literal('timer'),
|
|
50
|
+
prompt: Type.String(),
|
|
51
|
+
cron: Type.Optional(Type.String()),
|
|
52
|
+
delaySeconds: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
53
|
+
once: Type.Boolean(),
|
|
54
|
+
strategy: StrategySchema,
|
|
55
|
+
model: Type.Optional(Type.Object({ provider: Type.String(), id: Type.String(), thinking: Type.Optional(Type.String()) })),
|
|
56
|
+
trusted: Type.Optional(Type.Boolean()),
|
|
57
|
+
}),
|
|
58
|
+
Type.Object({
|
|
59
|
+
kind: Type.Literal('webhook'),
|
|
60
|
+
prompt: Type.String(),
|
|
61
|
+
slug: Type.String(),
|
|
62
|
+
strategy: Type.Optional(StrategySchema),
|
|
63
|
+
model: Type.Optional(Type.Object({ provider: Type.String(), id: Type.String(), thinking: Type.Optional(Type.String()) })),
|
|
64
|
+
trusted: Type.Optional(Type.Boolean()),
|
|
65
|
+
}),
|
|
33
66
|
]);
|
|
34
67
|
const SubscriptionSchema = Type.Object({ id: Type.String(), name: Type.String(), createdAt: Type.Number(), expiresAt: Type.Number(), config: ConfigSchema });
|
|
35
68
|
|
|
36
69
|
export type Subscription = Static<typeof SubscriptionSchema>;
|
|
37
70
|
type Config = Subscription['config'];
|
|
38
71
|
type TimerConfig = Extract<Config, { kind: 'timer' }>;
|
|
72
|
+
type WebhookConfig = Extract<Config, { kind: 'webhook' }>;
|
|
39
73
|
type Strategy = TimerConfig['strategy'];
|
|
40
74
|
|
|
41
|
-
interface Note {
|
|
42
|
-
at: number;
|
|
43
|
-
text: string;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
interface Live {
|
|
47
|
-
sub: Subscription;
|
|
48
|
-
timers: Set<ReturnType<typeof setTimeout>>;
|
|
49
|
-
lastEvent?: Note;
|
|
50
|
-
lastError?: Note;
|
|
51
|
-
baseline?: Map<number, PrSnapshot>;
|
|
52
|
-
polling?: boolean;
|
|
53
|
-
url?: string;
|
|
54
|
-
cron?: CronSchedule;
|
|
55
|
-
lastCronMinute?: number;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
75
|
export interface SubscriptionOptions {
|
|
59
76
|
/** Runs a prompt in a fresh background session (a `new_session` timer fire). */
|
|
60
|
-
runFresh: (prompt: string, name: string) => Promise<
|
|
77
|
+
runFresh: (prompt: string, name: string, meta: FreshMeta) => Promise<string | undefined> | string | undefined;
|
|
61
78
|
gh?: GhRunner;
|
|
62
79
|
pollIntervalMs?: number;
|
|
63
80
|
/** Routines listener port; defaults to PSTACK_ROUTINES_PORT, else 47913. 0 picks a free port. */
|
|
64
81
|
routinesPort?: number;
|
|
65
82
|
routinesDir?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Starts the durable supervisor for this workspace when no live lock exists.
|
|
85
|
+
* Default spawns `pstack-routines-supervisor` detached so timers and routines survive chat exit.
|
|
86
|
+
*/
|
|
87
|
+
ensureSupervisor?: (cwd: string) => Promise<void> | void;
|
|
88
|
+
/** How long create/restore wait for supervisor.lock after ensure (ms). Default 2000. */
|
|
89
|
+
supervisorReadyMs?: number;
|
|
66
90
|
}
|
|
67
91
|
|
|
68
92
|
const iso = (ms: number) => new Date(ms).toISOString();
|
|
@@ -72,19 +96,16 @@ const oneLine = (text: string, max = 200) => {
|
|
|
72
96
|
};
|
|
73
97
|
const errorText = (error: unknown) => oneLine(error instanceof Error ? error.message : String(error), 500);
|
|
74
98
|
|
|
75
|
-
function envPort(): number {
|
|
76
|
-
const raw = process.env['PSTACK_ROUTINES_PORT'];
|
|
77
|
-
const port = raw === undefined || raw === '' ? DEFAULT_ROUTINES_PORT : Number(raw);
|
|
78
|
-
return Number.isInteger(port) && port >= 0 && port < 65536 ? port : DEFAULT_ROUTINES_PORT;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
99
|
function oneShotError(tool: string): Error {
|
|
82
100
|
return new Error(`${tool} needs an interactive or RPC session: print and JSON runs exit when the agent settles, so nothing could wake this run or fire this subscription later. Do the work now instead.`);
|
|
83
101
|
}
|
|
84
102
|
|
|
85
|
-
function expiryOf(now: number, hours: number | undefined): number {
|
|
86
|
-
|
|
87
|
-
|
|
103
|
+
function expiryOf(now: number, hours: number | undefined, kind: Config['kind']): number {
|
|
104
|
+
// Cursor Automations run until they are disabled, so a timer or routine has no default expiry. A PR watch is this
|
|
105
|
+
// port's own surface and keeps a bounded default.
|
|
106
|
+
if (hours === undefined) return kind === 'github' ? now + DEFAULT_EXPIRY_MS : 0;
|
|
107
|
+
if (hours === 0) return 0;
|
|
108
|
+
if (!(hours > 0 && hours <= MAX_EXPIRY_HOURS)) throw new Error(`expiresInHours must be 0 (no expiry) and at most ${MAX_EXPIRY_HOURS}.`);
|
|
88
109
|
return now + hours * HOUR_MS;
|
|
89
110
|
}
|
|
90
111
|
|
|
@@ -130,7 +151,7 @@ function timerTarget(config: TimerConfig): string {
|
|
|
130
151
|
}
|
|
131
152
|
|
|
132
153
|
const GithubParams = Type.Object({
|
|
133
|
-
scope:
|
|
154
|
+
scope: Type.Enum(['pr', 'repo', 'author'] as const, { type: 'string', description: 'pr: one pull request (prUrl). repo: every open PR in repo, including PRs opened, closed, or merged. author: open PRs in repo by author.' }),
|
|
134
155
|
prUrl: Type.Optional(Type.String({ description: 'scope pr: the pull request URL, such as https://github.com/owner/repo/pull/123.' })),
|
|
135
156
|
repo: Type.Optional(Type.String({ description: 'scope repo or author: owner/name.' })),
|
|
136
157
|
author: Type.Optional(Type.String({ description: 'scope author: a GitHub login, or @me.' })),
|
|
@@ -145,17 +166,25 @@ const TimerParams = Type.Object({
|
|
|
145
166
|
delaySeconds: Type.Optional(Type.Integer({ minimum: 1, description: 'Fire this many seconds from now, and again every delaySeconds after that unless once is true.' })),
|
|
146
167
|
once: Type.Optional(Type.Boolean({ description: 'Fire only once, then end the timer. Default false.' })),
|
|
147
168
|
sessionStrategy: Type.Optional(
|
|
148
|
-
|
|
149
|
-
|
|
169
|
+
Type.Enum(['wake_self', 'new_session'] as const, {
|
|
170
|
+
type: 'string',
|
|
171
|
+
description: 'wake_self (default) queues the prompt for this owning session. new_session starts fresh work each fire. A live owner gets a background Task notification; offline execution records its outcome in list_subscriptions.',
|
|
150
172
|
}),
|
|
151
173
|
),
|
|
152
|
-
expiresInHours: Type.Optional(Type.Number({ description: `Hours until the timer ends;
|
|
174
|
+
expiresInHours: Type.Optional(Type.Number({ description: `Hours until the timer ends; 0 or omitted means it never expires, at most ${MAX_EXPIRY_HOURS}.` })),
|
|
153
175
|
});
|
|
154
176
|
|
|
155
177
|
const WebhookParams = Type.Object({
|
|
156
178
|
name: Type.String({ description: 'Routine name; its kebab-case form is the slug in the URL and the credential folder. Re-creating an existing name returns created: false.' }),
|
|
157
179
|
prompt: Type.String({ description: 'Instructions for each wake. Say the POST body is untrusted data and name the JSON fields the sender posts.' }),
|
|
158
|
-
|
|
180
|
+
sessionStrategy: Type.Optional(
|
|
181
|
+
Type.Enum(['wake_self', 'new_session'] as const, {
|
|
182
|
+
type: 'string',
|
|
183
|
+
description:
|
|
184
|
+
'wake_self (default) queues the event for this owning session, which parks while it is offline. new_session starts a fresh detached run per accepted POST, the way a hosted automation runs with no chat open; its outcome is recorded in list_subscriptions.',
|
|
185
|
+
}),
|
|
186
|
+
),
|
|
187
|
+
expiresInHours: Type.Optional(Type.Number({ description: `Hours until the routine ends; 0 or omitted means it never expires, at most ${MAX_EXPIRY_HOURS}.` })),
|
|
159
188
|
});
|
|
160
189
|
|
|
161
190
|
const UnsubscribeParams = Type.Object({ subscription: Type.String({ description: 'The id or name of a subscription from list_subscriptions.' }) });
|
|
@@ -163,225 +192,232 @@ const UnsubscribeParams = Type.Object({ subscription: Type.String({ description:
|
|
|
163
192
|
const text = (value: unknown) => ({ content: [{ type: 'text' as const, text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }], details: value });
|
|
164
193
|
|
|
165
194
|
export function createSubscriptions(pi: ExtensionAPI, options: SubscriptionOptions) {
|
|
166
|
-
const live = new Map<string, Live>();
|
|
167
|
-
const gh = options.gh ?? defaultGhRunner;
|
|
168
|
-
const pollMs = options.pollIntervalMs ?? MINUTE_MS;
|
|
169
195
|
const dir = options.routinesDir ?? routinesDir();
|
|
170
|
-
|
|
171
|
-
let
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
196
|
+
let workspaceCwd = canonicalPath(process.cwd());
|
|
197
|
+
let owner: { id: string; cwd: string; lease: Lease; notify: (message: string) => void } | undefined;
|
|
198
|
+
let ownerPoll: ReturnType<typeof setInterval> | undefined;
|
|
199
|
+
let fallback: Supervisor | undefined;
|
|
200
|
+
let starting: Promise<void> | undefined;
|
|
201
|
+
let draining = false;
|
|
202
|
+
let lastDrainError: string | undefined;
|
|
203
|
+
|
|
204
|
+
const persist = () => pi.appendEntry(SUBSCRIPTIONS_ENTRY, { subscriptions: readRegistry(workspaceCwd).subscriptions.filter((sub) => isDesired(sub)) });
|
|
205
|
+
|
|
206
|
+
const drain = () => {
|
|
207
|
+
const session = owner;
|
|
208
|
+
if (session === undefined || draining) return;
|
|
209
|
+
draining = true;
|
|
210
|
+
try {
|
|
211
|
+
const eligible = () => owner === session;
|
|
212
|
+
const registry = readRegistry(session.cwd);
|
|
213
|
+
const pending = registry.pending.filter((event) => {
|
|
214
|
+
if (event.retryAt !== undefined && Date.now() < event.retryAt) return false;
|
|
215
|
+
return registry.subscriptions.some((sub) => sub.id === event.subscriptionId && sub.ownerSessionId === session.id);
|
|
216
|
+
});
|
|
217
|
+
if (pending.length === 0) return;
|
|
218
|
+
deliverOwner(session.cwd, session.id, eligible, (sub, event) => {
|
|
219
|
+
pi.sendMessage({ customType: WAKE_TYPE, content: event.content, display: true, details: { id: sub.id, eventId: event.id, kind: sub.config.kind, name: sub.name } }, { triggerTurn: true, deliverAs: 'followUp' });
|
|
220
|
+
});
|
|
221
|
+
for (const event of pending) {
|
|
222
|
+
const claim = startFresh(session.cwd, event.id, session.id, eligible, (sub, pending) =>
|
|
223
|
+
options.runFresh(pending.content, sub.name, {
|
|
224
|
+
subscriptionId: sub.id,
|
|
225
|
+
cwd: session.cwd,
|
|
226
|
+
...(sub.config.kind !== 'github' && sub.config.model !== undefined ? { model: sub.config.model } : {}),
|
|
227
|
+
...(sub.config.kind !== 'github' && sub.config.trusted !== undefined ? { trusted: sub.config.trusted } : {}),
|
|
228
|
+
}),
|
|
229
|
+
);
|
|
230
|
+
if (claim !== undefined)
|
|
231
|
+
void claim.result
|
|
232
|
+
.then(
|
|
233
|
+
() => finishFresh(session.cwd, event.id, claim.token),
|
|
234
|
+
(cause: unknown) => finishFresh(session.cwd, event.id, claim.token, cause),
|
|
235
|
+
)
|
|
236
|
+
.catch((cause: unknown) => session.notify(`Subscription result could not be saved. ${errorText(cause)}`));
|
|
237
|
+
}
|
|
238
|
+
lastDrainError = undefined;
|
|
239
|
+
} catch (cause) {
|
|
240
|
+
const message = errorText(cause);
|
|
241
|
+
if (message !== lastDrainError) session.notify(`Subscription owner delivery failed. ${message}`);
|
|
242
|
+
lastDrainError = message;
|
|
243
|
+
} finally {
|
|
244
|
+
draining = false;
|
|
200
245
|
}
|
|
201
246
|
};
|
|
202
247
|
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
248
|
+
const ensureEngine = async () => {
|
|
249
|
+
if (starting !== undefined) return starting;
|
|
250
|
+
const cwd = workspaceCwd;
|
|
251
|
+
const session = owner;
|
|
252
|
+
const attempt = (async () => {
|
|
253
|
+
if (fallback !== undefined) {
|
|
254
|
+
await fallback.reconcile();
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (isSupervisorLive(cwd)) return;
|
|
258
|
+
const canDetach = options.routinesDir === undefined || options.routinesDir === routinesDir();
|
|
259
|
+
if (canDetach) {
|
|
260
|
+
const ensure = options.ensureSupervisor ?? ((workspace: string) => defaultEnsureSupervisor(workspace, options.routinesPort === undefined ? {} : { routinesPort: options.routinesPort }));
|
|
261
|
+
await ensure(cwd);
|
|
262
|
+
if (owner !== session || session === undefined) return;
|
|
263
|
+
if (isSupervisorLive(cwd) || (await waitForSupervisor(cwd, options.supervisorReadyMs ?? 2_000))) return;
|
|
264
|
+
}
|
|
265
|
+
if (owner !== session || session === undefined) return;
|
|
266
|
+
const engine = createSupervisor({
|
|
267
|
+
workspaceCwd: cwd,
|
|
268
|
+
runFresh: options.runFresh,
|
|
269
|
+
isDaemon: false,
|
|
270
|
+
ownerSessionId: session.id,
|
|
271
|
+
...(options.gh === undefined ? {} : { gh: options.gh }),
|
|
272
|
+
...(options.pollIntervalMs === undefined ? {} : { pollIntervalMs: options.pollIntervalMs }),
|
|
273
|
+
...(options.routinesPort === undefined ? {} : { routinesPort: options.routinesPort }),
|
|
274
|
+
...(options.routinesDir === undefined ? {} : { routinesDir: options.routinesDir }),
|
|
275
|
+
onAccepted: drain,
|
|
276
|
+
});
|
|
277
|
+
fallback = engine;
|
|
278
|
+
try {
|
|
279
|
+
const result = await engine.start();
|
|
280
|
+
if (owner !== session) engine.stop();
|
|
281
|
+
if (!result.started && fallback === engine) fallback = undefined;
|
|
282
|
+
} catch (cause) {
|
|
283
|
+
engine.stop();
|
|
284
|
+
if (fallback === engine) fallback = undefined;
|
|
285
|
+
throw cause;
|
|
286
|
+
}
|
|
287
|
+
})().finally(() => {
|
|
288
|
+
if (starting === attempt) starting = undefined;
|
|
289
|
+
});
|
|
290
|
+
starting = attempt;
|
|
291
|
+
return attempt;
|
|
209
292
|
};
|
|
210
293
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
294
|
+
const view = (sub: StoredSubscription) => {
|
|
295
|
+
const config = sub.config;
|
|
296
|
+
const base = { id: sub.id, name: sub.name, kind: config.kind, createdAt: iso(sub.createdAt), expiresAt: sub.expiresAt === 0 ? 'never' : iso(sub.expiresAt) };
|
|
297
|
+
if (config.kind === 'timer')
|
|
298
|
+
return { ...base, target: timerTarget(config), prompt: config.prompt, sessionStrategy: config.strategy, ...(config.cron === undefined ? { delaySeconds: config.delaySeconds } : { cron: config.cron }), once: config.once };
|
|
299
|
+
if (config.kind === 'github') return { ...base, target: targetText(config.target), ...config.target, sessionStrategy: 'wake_self' as Strategy };
|
|
300
|
+
const arm = readArm(workspaceCwd, sub);
|
|
301
|
+
const url = arm?.state === 'ready' ? arm.url : undefined;
|
|
302
|
+
return {
|
|
303
|
+
...base,
|
|
304
|
+
target: url ?? `(not listening) /routines/${config.slug}`,
|
|
305
|
+
url,
|
|
306
|
+
credentialFile: credentialFile(dir, config.slug),
|
|
307
|
+
slug: config.slug,
|
|
308
|
+
prompt: config.prompt,
|
|
309
|
+
sessionStrategy: config.strategy ?? ('wake_self' as Strategy),
|
|
310
|
+
};
|
|
216
311
|
};
|
|
217
312
|
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
};
|
|
313
|
+
const status = (sub: StoredSubscription) => ({
|
|
314
|
+
...(sub.lastEvent === undefined ? {} : { lastEvent: `${iso(sub.lastEvent.at)} ${sub.lastEvent.text}` }),
|
|
315
|
+
...(sub.lastError === undefined ? {} : { lastError: `${iso(sub.lastError.at)} ${sub.lastError.text}` }),
|
|
316
|
+
...(sub.lastOutcome === undefined ? {} : { lastOutcome: `${iso(sub.lastOutcome.at)} ${sub.lastOutcome.text}` }),
|
|
317
|
+
});
|
|
223
318
|
|
|
224
|
-
const
|
|
225
|
-
if (
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
}
|
|
234
|
-
if (config.once) remove(entry);
|
|
319
|
+
const shutdown = () => {
|
|
320
|
+
if (ownerPoll !== undefined) clearInterval(ownerPoll);
|
|
321
|
+
ownerPoll = undefined;
|
|
322
|
+
starting = undefined;
|
|
323
|
+
const previous = owner;
|
|
324
|
+
owner = undefined;
|
|
325
|
+
previous?.lease.release();
|
|
326
|
+
fallback?.stop();
|
|
327
|
+
fallback = undefined;
|
|
235
328
|
};
|
|
236
329
|
|
|
237
|
-
const
|
|
238
|
-
if (
|
|
239
|
-
|
|
240
|
-
const tick = () => {
|
|
241
|
-
if (expired(entry)) return;
|
|
242
|
-
const now = Date.now();
|
|
243
|
-
const minute = Math.floor(now / MINUTE_MS);
|
|
244
|
-
if (minute !== entry.lastCronMinute && cronMatches(schedule, new Date(now))) {
|
|
245
|
-
entry.lastCronMinute = minute;
|
|
246
|
-
fireTimer(entry, config);
|
|
247
|
-
if (!owns(entry)) return;
|
|
248
|
-
}
|
|
249
|
-
at(entry, (minute + 1) * MINUTE_MS, tick);
|
|
250
|
-
};
|
|
251
|
-
at(entry, (Math.floor(Date.now() / MINUTE_MS) + 1) * MINUTE_MS, tick);
|
|
330
|
+
const restore = (ctx: ExtensionContext) => {
|
|
331
|
+
if (isOneShot(ctx.mode)) {
|
|
332
|
+
shutdown();
|
|
252
333
|
return;
|
|
253
334
|
}
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
entry.polling = true;
|
|
272
|
-
try {
|
|
273
|
-
const after = await fetchPrs(gh, target);
|
|
274
|
-
if (!active || !owns(entry)) return;
|
|
275
|
-
if (entry.baseline !== undefined) {
|
|
276
|
-
const blocks = await pollChanges(gh, target, entry.baseline, after);
|
|
277
|
-
if (blocks.length > 0 && owns(entry))
|
|
278
|
-
wake(
|
|
279
|
-
entry,
|
|
280
|
-
[`[github] ${entry.sub.name}`, ...blocks].join('\n\n'),
|
|
281
|
-
blocks
|
|
282
|
-
.map((block) =>
|
|
283
|
-
block
|
|
284
|
-
.replace(/ \(https?:\/\/\S+\)/, '')
|
|
285
|
-
.replace(/\n- /g, ': ')
|
|
286
|
-
.replace(/\n/g, '; '),
|
|
287
|
-
)
|
|
288
|
-
.join(' | '),
|
|
289
|
-
);
|
|
335
|
+
const cwd = canonicalPath(ctx.cwd || process.cwd());
|
|
336
|
+
const id = ctx.sessionManager.getSessionId();
|
|
337
|
+
if (owner?.id === id && owner.cwd === cwd) {
|
|
338
|
+
drain();
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
shutdown();
|
|
342
|
+
workspaceCwd = cwd;
|
|
343
|
+
const lease = acquireLease(ownerLockPath(cwd, id));
|
|
344
|
+
if (lease === undefined) {
|
|
345
|
+
ctx.ui.notify('Subscription owner delivery unavailable. Another live process owns this exact session.', 'error');
|
|
346
|
+
if (ownerPoll === undefined) {
|
|
347
|
+
ownerPoll = setInterval(() => {
|
|
348
|
+
if (owner === undefined) restore(ctx);
|
|
349
|
+
else drain();
|
|
350
|
+
}, 250);
|
|
351
|
+
ownerPoll.unref?.();
|
|
290
352
|
}
|
|
291
|
-
|
|
292
|
-
entry.baseline = after;
|
|
293
|
-
delete entry.lastError;
|
|
294
|
-
} catch (error) {
|
|
295
|
-
entry.lastError = { at: Date.now(), text: errorText(error) };
|
|
296
|
-
} finally {
|
|
297
|
-
entry.polling = false;
|
|
353
|
+
return;
|
|
298
354
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
if (
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const onWebhook = (entry: Live, prompt: string) => (event: WebhookEvent) => {
|
|
312
|
-
if (!owns(entry) || expired(entry)) return;
|
|
313
|
-
wake(entry, [`[routine] ${entry.sub.name}`, prompt, webhookEventBlock(event)].join('\n\n'), `POST, body sha256 ${event.bodyDigest.slice(0, 12)}`);
|
|
314
|
-
};
|
|
315
|
-
|
|
316
|
-
const armWebhook = async (entry: Live, slug: string, prompt: string) => {
|
|
317
|
-
const credentialFile = ensureCredentials(dir, slug);
|
|
318
|
-
server.routes.set(slug, { slug, credentialFile, onEvent: onWebhook(entry, prompt) });
|
|
319
|
-
try {
|
|
320
|
-
entry.url = await server.url(slug);
|
|
321
|
-
delete entry.lastError;
|
|
322
|
-
} catch (error) {
|
|
323
|
-
server.routes.delete(slug);
|
|
324
|
-
entry.lastError = { at: Date.now(), text: errorText(error) };
|
|
325
|
-
throw error;
|
|
355
|
+
const notify = ctx.ui.notify.bind(ctx.ui);
|
|
356
|
+
owner = { id, cwd, lease, notify: (message) => notify(message, 'error') };
|
|
357
|
+
drain();
|
|
358
|
+
ownerPoll = setInterval(drain, 250);
|
|
359
|
+
ownerPoll.unref?.();
|
|
360
|
+
const registry = readRegistry(cwd);
|
|
361
|
+
if (subscriptionsFromBranch(ctx.sessionManager.getBranch()).some((sub) => !registry.subscriptions.some((stored) => stored.id === sub.id))) {
|
|
362
|
+
notify('Historical subscription receipts are inactive. Recreate missing subscriptions with the subscribe tools.', 'info');
|
|
363
|
+
}
|
|
364
|
+
if (registry.subscriptions.some((sub) => isDesired(sub))) {
|
|
365
|
+
void ensureEngine().catch((cause: unknown) => notify(`Subscriptions could not start. ${errorText(cause)}`, 'error'));
|
|
326
366
|
}
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
const expiryTimer = (entry: Live) => at(entry, entry.sub.expiresAt, () => expired(entry));
|
|
330
|
-
|
|
331
|
-
const arm = async (entry: Live) => {
|
|
332
|
-
const { config } = entry.sub;
|
|
333
|
-
expiryTimer(entry);
|
|
334
|
-
if (config.kind === 'timer') armTimer(entry, config);
|
|
335
|
-
else if (config.kind === 'github') await armGithub(entry, config.target);
|
|
336
|
-
else await armWebhook(entry, config.slug, config.prompt);
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
const view = (entry: Live) => {
|
|
340
|
-
const { sub } = entry;
|
|
341
|
-
const { config } = sub;
|
|
342
|
-
const base = { id: sub.id, name: sub.name, kind: config.kind, createdAt: iso(sub.createdAt), expiresAt: iso(sub.expiresAt) };
|
|
343
|
-
if (config.kind === 'timer')
|
|
344
|
-
return { ...base, target: timerTarget(config), prompt: config.prompt, sessionStrategy: config.strategy, ...(config.cron === undefined ? { delaySeconds: config.delaySeconds } : { cron: config.cron }), once: config.once };
|
|
345
|
-
if (config.kind === 'github') return { ...base, target: targetText(config.target), ...config.target, sessionStrategy: 'wake_self' as Strategy };
|
|
346
|
-
return { ...base, target: entry.url ?? `(not listening) /routines/${config.slug}`, url: entry.url, credentialFile: credentialFile(dir, config.slug), slug: config.slug, prompt: config.prompt, sessionStrategy: 'wake_self' as Strategy };
|
|
347
367
|
};
|
|
348
368
|
|
|
349
369
|
const create = async (ctx: ExtensionContext, tool: string, name: string, config: Config, hours: number | undefined) => {
|
|
350
370
|
if (isOneShot(ctx.mode)) throw oneShotError(tool);
|
|
351
371
|
if (name.trim() === '') throw new Error('name must not be empty.');
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
if (config.kind === 'webhook') {
|
|
358
|
-
const clash = [...live.values()].find((entry) => entry.sub.config.kind === 'webhook' && entry.sub.config.slug === config.slug);
|
|
359
|
-
if (clash !== undefined) throw new Error(`Routine "${clash.sub.name}" already uses the slug ${config.slug}.`);
|
|
360
|
-
}
|
|
372
|
+
const cwd = canonicalPath(ctx.cwd || process.cwd());
|
|
373
|
+
const id = ctx.sessionManager.getSessionId();
|
|
374
|
+
if (owner?.id !== id || owner.cwd !== cwd) restore(ctx);
|
|
375
|
+
if (owner === undefined) throw new Error('Subscription owner delivery unavailable for this session.');
|
|
376
|
+
const session = owner;
|
|
361
377
|
const now = Date.now();
|
|
362
|
-
const
|
|
363
|
-
|
|
378
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
379
|
+
const result = createDesired(cwd, {
|
|
380
|
+
id: `sub-${randomBytes(12).toString('hex')}`,
|
|
381
|
+
name,
|
|
382
|
+
createdAt: now,
|
|
383
|
+
expiresAt: expiryOf(now, hours, config.kind),
|
|
384
|
+
config,
|
|
385
|
+
ownerSessionId: id,
|
|
386
|
+
...(file === undefined ? {} : { ownerSessionFile: canonicalPath(file) }),
|
|
387
|
+
});
|
|
388
|
+
let sub = result.subscription;
|
|
389
|
+
if (sub.config.kind !== config.kind) throw new Error(`A ${sub.config.kind} subscription is already named "${name}". Pick another name or unsubscribe it first.`);
|
|
364
390
|
try {
|
|
365
|
-
await
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
throw
|
|
391
|
+
await ensureEngine();
|
|
392
|
+
if (owner !== session) throw new Error(`Subscription ${sub.id} owner session changed while arming.`);
|
|
393
|
+
await waitForArm(cwd, sub, options.supervisorReadyMs ?? 2_000);
|
|
394
|
+
if (owner !== session) throw new Error(`Subscription ${sub.id} owner session changed while arming.`);
|
|
395
|
+
} catch (cause) {
|
|
396
|
+
if (result.created) {
|
|
397
|
+
cancelDesired(cwd, sub.id);
|
|
398
|
+
if (owner === session) await fallback?.reconcile();
|
|
399
|
+
}
|
|
400
|
+
throw cause;
|
|
369
401
|
}
|
|
370
|
-
|
|
371
|
-
|
|
402
|
+
sub = readRegistry(cwd).subscriptions.find((entry) => entry.id === sub.id) ?? sub;
|
|
403
|
+
if (result.created) persist();
|
|
404
|
+
return {
|
|
405
|
+
created: result.created,
|
|
406
|
+
...view(sub),
|
|
407
|
+
...status(sub),
|
|
408
|
+
...(fallback === undefined ? {} : { durability: 'in-process; start pstack-routines-supervisor for chat-exit survival' }),
|
|
409
|
+
...(sub.ownerSessionFile === undefined && !runsDetached(sub) ? { ownerWarning: 'Owner session is unsaved. Offline owner wakes cannot resume after this process exits.' } : {}),
|
|
410
|
+
};
|
|
372
411
|
};
|
|
373
412
|
|
|
374
|
-
const status = (entry: Live) => ({
|
|
375
|
-
...(entry.lastEvent === undefined ? {} : { lastEvent: `${iso(entry.lastEvent.at)} ${entry.lastEvent.text}` }),
|
|
376
|
-
...(entry.lastError === undefined ? {} : { lastError: `${iso(entry.lastError.at)} ${entry.lastError.text}` }),
|
|
377
|
-
});
|
|
378
|
-
|
|
379
413
|
const listText = () => {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
414
|
+
const registry = readRegistry(workspaceCwd);
|
|
415
|
+
const visible = visibleSubscriptions(registry);
|
|
416
|
+
if (visible.length === 0) return 'No subscriptions.';
|
|
417
|
+
return visible
|
|
418
|
+
.map((sub) => {
|
|
419
|
+
const item = view(sub);
|
|
420
|
+
const state = status(sub);
|
|
385
421
|
return [
|
|
386
422
|
`${item.id} ${item.kind} "${item.name}"`,
|
|
387
423
|
` target: ${item.target}`,
|
|
@@ -389,71 +425,49 @@ export function createSubscriptions(pi: ExtensionAPI, options: SubscriptionOptio
|
|
|
389
425
|
` created: ${item.createdAt} expires: ${item.expiresAt}`,
|
|
390
426
|
` last event: ${state.lastEvent ?? 'none'}`,
|
|
391
427
|
...(state.lastError === undefined ? [] : [` last error: ${state.lastError}`]),
|
|
428
|
+
...(state.lastOutcome === undefined ? [] : [` last outcome: ${state.lastOutcome}`]),
|
|
429
|
+
...(registry.pending.some((event) => event.subscriptionId === sub.id) ? [' delivery: pending'] : []),
|
|
392
430
|
].join('\n');
|
|
393
431
|
})
|
|
394
432
|
.join('\n');
|
|
395
433
|
};
|
|
396
434
|
|
|
397
435
|
const routinesText = () => {
|
|
398
|
-
const routines =
|
|
436
|
+
const routines = visibleSubscriptions(readRegistry(workspaceCwd)).filter((sub) => sub.config.kind === 'webhook');
|
|
399
437
|
if (routines.length === 0) return 'No webhook routines.';
|
|
400
438
|
return routines
|
|
401
|
-
.map((
|
|
402
|
-
const item = view(
|
|
403
|
-
const
|
|
404
|
-
|
|
439
|
+
.map((sub) => {
|
|
440
|
+
const item = view(sub) as ReturnType<typeof view> & { url?: string; credentialFile?: string };
|
|
441
|
+
const arm = readArm(workspaceCwd, sub);
|
|
442
|
+
const enabled = isDesired(sub) && arm?.state === 'ready' ? 'enabled' : `disabled${sub.lastError === undefined ? '' : ` (${sub.lastError.text})`}`;
|
|
443
|
+
return [`${item.name} [${enabled}]`, ` url: ${item.url ?? 'none'}`, ` strategy: ${item.sessionStrategy}`, ` credential file: ${item.credentialFile}`, ` expires: ${item.expiresAt}`].join('\n');
|
|
405
444
|
})
|
|
406
445
|
.join('\n');
|
|
407
446
|
};
|
|
408
447
|
|
|
409
|
-
const
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
448
|
+
const unsubscribe = async (key: string) => {
|
|
449
|
+
const sub = cancelDesired(workspaceCwd, key);
|
|
450
|
+
if (sub === undefined) throw new Error(`No subscription has the id or name "${key}". list_subscriptions shows them.`);
|
|
451
|
+
await fallback?.reconcile();
|
|
452
|
+
persist();
|
|
453
|
+
return { removed: true, id: sub.id, name: sub.name, kind: sub.config.kind };
|
|
413
454
|
};
|
|
414
455
|
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
for (const [id, entry] of live) if (entry.baseline !== undefined) baselines.set(id, new Map(entry.baseline));
|
|
418
|
-
stopAll();
|
|
419
|
-
active = true;
|
|
420
|
-
if (isOneShot(ctx.mode)) return;
|
|
421
|
-
const stored = subscriptionsFromBranch(ctx.sessionManager.getBranch());
|
|
422
|
-
const now = Date.now();
|
|
423
|
-
for (const sub of stored) {
|
|
424
|
-
if (sub.expiresAt <= now) continue;
|
|
425
|
-
const baseline = baselines.get(sub.id);
|
|
426
|
-
live.set(sub.id, { sub, timers: new Set(), ...(baseline === undefined ? {} : { baseline }) });
|
|
427
|
-
}
|
|
428
|
-
if (live.size !== stored.length) persist();
|
|
429
|
-
for (const entry of live.values()) {
|
|
430
|
-
arm(entry).catch(() => undefined);
|
|
431
|
-
}
|
|
432
|
-
};
|
|
456
|
+
return { create, unsubscribe, listText, routinesText, restore, shutdown };
|
|
457
|
+
}
|
|
433
458
|
|
|
434
|
-
|
|
435
|
-
const entry = live.get(key) ?? byName(key);
|
|
436
|
-
if (entry === undefined) throw new Error(`No subscription has the id or name "${key}". list_subscriptions shows them.`);
|
|
437
|
-
remove(entry);
|
|
438
|
-
return { removed: true, id: entry.sub.id, name: entry.sub.name, kind: entry.sub.config.kind };
|
|
439
|
-
};
|
|
459
|
+
const WAKE_COLLAPSED_LINES = 10;
|
|
440
460
|
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
routinesText,
|
|
446
|
-
restore,
|
|
447
|
-
shutdown: () => {
|
|
448
|
-
active = false;
|
|
449
|
-
stopAll();
|
|
450
|
-
},
|
|
451
|
-
};
|
|
461
|
+
export function subscriptionWakeText(message: { content: string | { type: string; text?: string }[] }, expanded: boolean): string {
|
|
462
|
+
const raw = typeof message.content === 'string' ? message.content : message.content.map((part) => (part.type === 'text' ? (part.text ?? '') : '')).join('\n');
|
|
463
|
+
const lines = raw.split('\n');
|
|
464
|
+
return (expanded || lines.length <= WAKE_COLLAPSED_LINES ? lines : [...lines.slice(0, WAKE_COLLAPSED_LINES), `… ${lines.length - WAKE_COLLAPSED_LINES} more lines`]).join('\n');
|
|
452
465
|
}
|
|
453
466
|
|
|
454
467
|
/** Subscriptions (GitHub PR polls, timers, webhook routines) that wake this session or start fresh ones. */
|
|
455
468
|
export function registerSubscriptions(pi: ExtensionAPI, options: SubscriptionOptions): ReturnType<typeof createSubscriptions> {
|
|
456
469
|
const subs = createSubscriptions(pi, options);
|
|
470
|
+
pi.registerMessageRenderer?.(WAKE_TYPE, (message, renderOptions) => new Text(subscriptionWakeText(message, renderOptions.expanded), 0, 0));
|
|
457
471
|
pi.on('session_start', (_event, ctx) => subs.restore(ctx));
|
|
458
472
|
pi.on('session_tree', (_event, ctx) => subs.restore(ctx));
|
|
459
473
|
pi.on('session_shutdown', () => subs.shutdown());
|
|
@@ -465,6 +479,7 @@ export function registerSubscriptions(pi: ExtensionAPI, options: SubscriptionOpt
|
|
|
465
479
|
'Watch GitHub pull requests with gh and wake this session when one changes: state (merged, closed, reopened), head SHA, mergeability, review decision, new reviews or comments, or a check concluding. The first poll only records a baseline. Polls every minute until unsubscribed or expired.',
|
|
466
480
|
promptSnippet: 'Wake this session when a GitHub PR changes',
|
|
467
481
|
parameters: GithubParams,
|
|
482
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
468
483
|
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
469
484
|
const target =
|
|
470
485
|
params.scope === 'pr'
|
|
@@ -482,9 +497,10 @@ export function registerSubscriptions(pi: ExtensionAPI, options: SubscriptionOpt
|
|
|
482
497
|
name: 'subscribe_timer',
|
|
483
498
|
label: 'Subscribe: timer',
|
|
484
499
|
description:
|
|
485
|
-
'Fire a prompt on a 5-field cron schedule (local time) or after delaySeconds (repeating unless once). wake_self
|
|
500
|
+
'Fire a prompt on a 5-field cron schedule (local time) or after delaySeconds (repeating unless once). wake_self queues the prompt for this owning session, including while offline. new_session uses a background Task while the owner is live, or a detached run with recorded status while offline. Re-subscribing an existing name returns created: false and changes nothing.',
|
|
486
501
|
promptSnippet: 'Schedule a prompt with cron or a delay',
|
|
487
502
|
parameters: TimerParams,
|
|
503
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
488
504
|
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
489
505
|
if (isOneShot(ctx.mode)) throw oneShotError('subscribe_timer');
|
|
490
506
|
if ((params.cron === undefined) === (params.delaySeconds === undefined)) throw new Error('Pass exactly one of cron or delaySeconds.');
|
|
@@ -495,6 +511,8 @@ export function registerSubscriptions(pi: ExtensionAPI, options: SubscriptionOpt
|
|
|
495
511
|
...(params.cron === undefined ? { delaySeconds: params.delaySeconds ?? 1 } : { cron: params.cron.trim() }),
|
|
496
512
|
once: params.once ?? false,
|
|
497
513
|
strategy: params.sessionStrategy ?? 'wake_self',
|
|
514
|
+
...(ctx.model === undefined ? {} : { model: { provider: ctx.model.provider, id: ctx.model.id, ...(ctx.thinkingLevel === undefined ? {} : { thinking: ctx.thinkingLevel }) } }),
|
|
515
|
+
trusted: ctx.isProjectTrusted(),
|
|
498
516
|
};
|
|
499
517
|
return text(await subs.create(ctx, 'subscribe_timer', params.name, config, params.expiresInHours));
|
|
500
518
|
},
|
|
@@ -504,19 +522,28 @@ export function registerSubscriptions(pi: ExtensionAPI, options: SubscriptionOpt
|
|
|
504
522
|
name: 'subscribe_webhook',
|
|
505
523
|
label: 'Subscribe: webhook routine',
|
|
506
524
|
description:
|
|
507
|
-
'Create a webhook routine: a local URL (http://127.0.0.1:<port>/routines/<slug>) that
|
|
525
|
+
'Create a webhook routine: a local URL (http://127.0.0.1:<port>/routines/<slug>) that fires when a sender POSTs a JSON object with the routine key in X-Automation-Key or Authorization: Bearer. wake_self (default) wakes this owning session with a [routine] turn. new_session starts a fresh detached run per accepted POST, so it keeps working with no chat open. The result gives the URL and the credential file holding the key (field "key"); the key itself is never shown. Copy it from that file into the sender without printing it.',
|
|
508
526
|
promptSnippet: 'Create a webhook routine that wakes this session',
|
|
509
527
|
parameters: WebhookParams,
|
|
528
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
510
529
|
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
511
530
|
if (isOneShot(ctx.mode)) throw oneShotError('subscribe_webhook');
|
|
512
|
-
|
|
531
|
+
const config: WebhookConfig = {
|
|
532
|
+
kind: 'webhook',
|
|
533
|
+
prompt: params.prompt,
|
|
534
|
+
slug: routineSlug(params.name),
|
|
535
|
+
strategy: params.sessionStrategy ?? 'wake_self',
|
|
536
|
+
...(ctx.model === undefined ? {} : { model: { provider: ctx.model.provider, id: ctx.model.id, ...(ctx.thinkingLevel === undefined ? {} : { thinking: ctx.thinkingLevel }) } }),
|
|
537
|
+
trusted: ctx.isProjectTrusted(),
|
|
538
|
+
};
|
|
539
|
+
return text(await subs.create(ctx, 'subscribe_webhook', params.name, config, params.expiresInHours));
|
|
513
540
|
},
|
|
514
541
|
});
|
|
515
542
|
|
|
516
543
|
pi.registerTool({
|
|
517
544
|
name: 'list_subscriptions',
|
|
518
545
|
label: 'Subscriptions',
|
|
519
|
-
description: "List this
|
|
546
|
+
description: "List this workspace's subscriptions (GitHub PR watches, timers, webhook routines) with id, kind, target, strategy, created and expiry times, and the last event or error.",
|
|
520
547
|
promptSnippet: 'List subscriptions',
|
|
521
548
|
parameters: Type.Object({}),
|
|
522
549
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
@@ -531,8 +558,9 @@ export function registerSubscriptions(pi: ExtensionAPI, options: SubscriptionOpt
|
|
|
531
558
|
description: 'End a subscription by id or name.',
|
|
532
559
|
promptSnippet: 'End a subscription',
|
|
533
560
|
parameters: UnsubscribeParams,
|
|
561
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
534
562
|
async execute(_id, params) {
|
|
535
|
-
return text(subs.unsubscribe(params.subscription));
|
|
563
|
+
return text(await subs.unsubscribe(params.subscription));
|
|
536
564
|
},
|
|
537
565
|
});
|
|
538
566
|
|