@picassohq/cli 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3062 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +215 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6280 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/packages/picasso-lean-context/timeline.js +418 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +912 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1083 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +142 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +891 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +412 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +116 -0
- package/runtime/packages/picasso-web-search/format.js +42 -0
- package/runtime/packages/picasso-web-search/index.js +71 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +156 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6280 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +912 -0
- package/runtime/plugins/picasso-model-router/index.js +1083 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +412 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +116 -0
- package/runtime/plugins/picasso-web-search/format.js +42 -0
- package/runtime/plugins/picasso-web-search/index.js +71 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +156 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +38580 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1400 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
// @picasso/trackers — Linear / Jira / GitHub / GitLab issue links for dsh threads (B10).
|
|
2
|
+
//
|
|
3
|
+
// Creates and links tracker issues from a Picasso thread, keeps the link beside the sessions root, and
|
|
4
|
+
// refreshes the issue's status on demand — without the agent doing it in-band. One Host Remote service
|
|
5
|
+
// (`tracker/*`), bound for the Typert gateway:
|
|
6
|
+
//
|
|
7
|
+
// providers() -> {providers:[{id, title, kind, tool?, state, detail?}]}
|
|
8
|
+
// state: ready | signed-out | missing | unconfigured.
|
|
9
|
+
// link(sessionId, provider, ref, cwd?) -> entry — ref parses per provider: GitHub `owner/repo#N` or an
|
|
10
|
+
// issue URL, GitLab `group/sub/repo#N` or `…/-/issues/N`,
|
|
11
|
+
// Linear `ENG-123` or a linear.app URL, Jira `PROJ-123` or a
|
|
12
|
+
// /browse/ URL. The provider's own lookup runs before the link
|
|
13
|
+
// is saved, so a bad ref answers with the provider's own error.
|
|
14
|
+
// unlink(sessionId) -> {sessionId, linked:false} — idempotent.
|
|
15
|
+
// create(sessionId, provider, title, body?, cwd?, repo?) -> entry — files the issue on the provider and
|
|
16
|
+
// links it to the thread in the same call. gh/glab need `repo`
|
|
17
|
+
// (arg or `providers.<id>.repo` config) or `cwd` inside the
|
|
18
|
+
// checkout; Linear needs `providers.linear.team`, Jira
|
|
19
|
+
// `providers.jira.project`.
|
|
20
|
+
// status(sessionId) -> {linked:false} | {linked:true, …entry, stale?, error?} — a
|
|
21
|
+
// refresh failure keeps the stored entry and reports `stale`
|
|
22
|
+
// plus the provider's message; the link is never dropped.
|
|
23
|
+
// list() -> {links:{sessionId: entry}} — the whole registry; clients
|
|
24
|
+
// filter it against the session list (trashed threads keep
|
|
25
|
+
// their row until the sidecar outlives them — hiding orphans
|
|
26
|
+
// is the caller's job).
|
|
27
|
+
//
|
|
28
|
+
// An entry is `{provider, ref, url, title?, state, stateLabel?, linkedAt, checkedAt, data}` where `state`
|
|
29
|
+
// normalizes to `open | done | canceled` for the chip's color and `stateLabel` keeps the provider's own
|
|
30
|
+
// words ("In Progress"); `data` holds the adapter's lookup key (repo+number, identifier, key).
|
|
31
|
+
//
|
|
32
|
+
// Credentials: GitHub/GitLab ride the person's `gh`/`glab` sign-in (the CLIs own the tokens — nothing is
|
|
33
|
+
// stored). Linear/Jira read `providers.<id>.*` plugin config — `settings/mutate` on this entry's ns
|
|
34
|
+
// (`picasso-trackers`) writes it live; `apiKey`/`token` are `role('secret')` so `settings/describe` never
|
|
35
|
+
// echoes them, and an `env:VAR` value resolves against the engine's environment at call time instead of
|
|
36
|
+
// persisting a raw token. No `tracker/*` answer ever carries a credential: provider readiness reports
|
|
37
|
+
// only whether a value is set.
|
|
38
|
+
//
|
|
39
|
+
// All CLI work is argv-only `execFile` — no shell string is built from user data — with
|
|
40
|
+
// `GH_PROMPT_DISABLED`/`GLAB_PROMPT_DISABLED`/`GIT_TERMINAL_PROMPT` so a would-be question errors instead
|
|
41
|
+
// of hanging, bounded timeouts, and a login-shell `command -v` probe (plus a PATH scan and the usual
|
|
42
|
+
// Homebrew spots) so a CLI the engine's inherited PATH misses is still found.
|
|
43
|
+
//
|
|
44
|
+
// Zero runtime dependencies on purpose, like @picasso/session-lifecycle: the Remote surface uses the
|
|
45
|
+
// gateway's source-mode markers (`@deepseek-ai/dsh-typert-protocol`'s `@Remote` descriptor) and failures
|
|
46
|
+
// are structural dsh RemoteErrors (`isDSHRemoteError`, code `tracker/<code>`). The `Config` schema is
|
|
47
|
+
// loaded from the bundled dsh's own `@deepseek-ai/schemastery` when it resolves (the Host's argv[1] or a
|
|
48
|
+
// `dsh` on PATH anchors `createRequire`); without it the plugin still runs — `settings/mutate` then just
|
|
49
|
+
// answers dsh's "no configurable plugin entry".
|
|
50
|
+
import { execFile } from 'node:child_process';
|
|
51
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
52
|
+
import { mkdir, rename, writeFile } from 'node:fs/promises';
|
|
53
|
+
import { createRequire } from 'node:module';
|
|
54
|
+
import { homedir } from 'node:os';
|
|
55
|
+
import { delimiter, dirname, join, resolve } from 'node:path';
|
|
56
|
+
|
|
57
|
+
export const name = 'picasso-trackers';
|
|
58
|
+
/** The dsh release this plugin is written and tested against (Picasso pins the engine to it). */
|
|
59
|
+
export const dshTarget = '0.2.2-rc.3';
|
|
60
|
+
export const SERVICE_KEY = 'tracker';
|
|
61
|
+
export const SIDECAR_FILENAME = 'picasso-trackers.json';
|
|
62
|
+
const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
|
|
63
|
+
const PROVIDER_IDS = /** @type {const} */ (['github', 'gitlab', 'linear', 'jira']);
|
|
64
|
+
const CLI_TIMEOUT_MS = 10_000;
|
|
65
|
+
const ISSUE_TIMEOUT_MS = 60_000;
|
|
66
|
+
const HTTP_TIMEOUT_MS = 15_000;
|
|
67
|
+
/** Tool homes a GUI-launched engine's PATH typically misses. */
|
|
68
|
+
const TOOL_DIRS = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'];
|
|
69
|
+
|
|
70
|
+
/** A dsh RemoteError, identified structurally by the gateway (`remoteErrorOf`), so the code reaches the client. */
|
|
71
|
+
export class TrackerError extends Error {
|
|
72
|
+
constructor(code, message, details = {}) {
|
|
73
|
+
super(message);
|
|
74
|
+
this.name = 'RemoteError';
|
|
75
|
+
this.code = `tracker/${code}`;
|
|
76
|
+
this.details = details;
|
|
77
|
+
this.isDSHRemoteError = true;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
82
|
+
const emptyState = () => ({ version: 1, links: {} });
|
|
83
|
+
|
|
84
|
+
/** One bounded argv run: `{code, output}` — combined stdout+stderr, `code` null on spawn failure/timeout. */
|
|
85
|
+
function execArgv(file, args, options = {}) {
|
|
86
|
+
return new Promise((resolveRun) => {
|
|
87
|
+
execFile(file, args, {
|
|
88
|
+
cwd: options.cwd,
|
|
89
|
+
env: options.env,
|
|
90
|
+
timeout: options.timeoutMs ?? CLI_TIMEOUT_MS,
|
|
91
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
92
|
+
windowsHide: true,
|
|
93
|
+
}, (error, stdout, stderr) => {
|
|
94
|
+
const code = error == null ? 0 : typeof error.code === 'number' ? error.code : null;
|
|
95
|
+
resolveRun({ code, output: `${stdout ?? ''}${stderr ?? ''}` });
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** One HTTP call: `{status, text}` — bounded; transport failures resolve as `{status: 0}`. */
|
|
101
|
+
async function httpRequest(url, options = {}) {
|
|
102
|
+
try {
|
|
103
|
+
const response = await fetch(url, {
|
|
104
|
+
method: options.method ?? 'GET',
|
|
105
|
+
headers: options.headers,
|
|
106
|
+
body: options.body,
|
|
107
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? HTTP_TIMEOUT_MS),
|
|
108
|
+
});
|
|
109
|
+
return { status: response.status, text: await response.text() };
|
|
110
|
+
} catch (error) {
|
|
111
|
+
return { status: 0, text: String(error?.message ?? error) };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The env a tracker CLI sees: prompts disabled so a question errors instead of hanging. */
|
|
116
|
+
function cliEnv(env) {
|
|
117
|
+
const path = [...TOOL_DIRS, ...(env.PATH ?? '').split(delimiter)]
|
|
118
|
+
.filter((dir, index, all) => dir && all.indexOf(dir) === index)
|
|
119
|
+
.join(delimiter);
|
|
120
|
+
return {
|
|
121
|
+
...env,
|
|
122
|
+
PATH: path,
|
|
123
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
124
|
+
GH_PROMPT_DISABLED: '1',
|
|
125
|
+
GLAB_PROMPT_DISABLED: '1',
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The last `https://…` token in a CLI's output, angle/quote cruft trimmed. */
|
|
130
|
+
export function lastHttpURL(output, marker) {
|
|
131
|
+
for (const token of String(output).split(/\s+/).reverse()) {
|
|
132
|
+
const trimmed = token.replace(/^["'<([{]+|["'>)\]}.,;:!?]+$/g, '');
|
|
133
|
+
if (/^https?:\/\//.test(trimmed) && (marker === undefined || trimmed.includes(marker))) return trimmed;
|
|
134
|
+
}
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** An error body's human line — provider JSON shapes first, then the last text lines. */
|
|
139
|
+
export function errorTail(text, maxChars = 600) {
|
|
140
|
+
const raw = String(text ?? '').trim();
|
|
141
|
+
if (raw.startsWith('{')) {
|
|
142
|
+
try {
|
|
143
|
+
const parsed = JSON.parse(raw);
|
|
144
|
+
const line = Array.isArray(parsed?.errors) && parsed.errors.length > 0
|
|
145
|
+
? (typeof parsed.errors[0] === 'string' ? parsed.errors[0] : parsed.errors[0]?.message)
|
|
146
|
+
: Array.isArray(parsed?.errorMessages) && parsed.errorMessages.length > 0
|
|
147
|
+
? parsed.errorMessages[0]
|
|
148
|
+
: isRecord(parsed?.errors) && Object.keys(parsed.errors).length > 0
|
|
149
|
+
? `${Object.keys(parsed.errors)[0]}: ${Object.values(parsed.errors)[0]}`
|
|
150
|
+
: typeof parsed?.message === 'string'
|
|
151
|
+
? parsed.message
|
|
152
|
+
: undefined;
|
|
153
|
+
if (line) return line.slice(0, maxChars);
|
|
154
|
+
} catch {
|
|
155
|
+
// not JSON after all — fall through to the tail
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const lines = raw.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
159
|
+
return lines.slice(-4).join('\n').slice(-maxChars);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ── Ref parsing ────────────────────────────────────────────────────────────────────────────────────────
|
|
163
|
+
|
|
164
|
+
const LINEAR_KEY = /^[A-Za-z][A-Za-z0-9]*-\d+$/;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Parse `input` into the provider's lookup key. Returns `{ref, data}` — the canonical display ref plus
|
|
168
|
+
* the adapter's own fields — or throws `tracker/bad-ref` with the provider's accepted forms. `context`
|
|
169
|
+
* may carry `{repo}` (an explicit -R target or configured default) for bare `#N`/`N` refs.
|
|
170
|
+
*/
|
|
171
|
+
export function parseRef(provider, input, context = {}) {
|
|
172
|
+
const text = String(input ?? '').trim();
|
|
173
|
+
if (!text) throw new TrackerError('bad-request', 'link needs a ref — an issue id, key or URL.', { provider });
|
|
174
|
+
const bare = /^#?(\d+)$/.exec(text);
|
|
175
|
+
switch (provider) {
|
|
176
|
+
case 'github': {
|
|
177
|
+
let match = /^https?:\/\/(?:www\.)?github\.com\/([^/?#]+\/[^/?#]+)\/issues\/(\d+)/i.exec(text);
|
|
178
|
+
if (match) return { ref: `${match[1]}#${match[2]}`, data: { repo: match[1], number: Number(match[2]) } };
|
|
179
|
+
match = /^([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?\/[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)#(\d+)$/.exec(text);
|
|
180
|
+
if (match) return { ref: `${match[1]}#${match[2]}`, data: { repo: match[1], number: Number(match[2]) } };
|
|
181
|
+
if (bare) {
|
|
182
|
+
const repo = context.repo;
|
|
183
|
+
if (typeof repo === 'string' && /^[^\s/]+\/[^\s/]+$/.test(repo)) {
|
|
184
|
+
return { ref: `${repo}#${bare[1]}`, data: { repo, number: Number(bare[1]) } };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
throw new TrackerError('bad-ref', `GitHub issues link as owner/repo#N or a github.com/…/issues/N URL — got ${JSON.stringify(text.slice(0, 120))}.`, { provider });
|
|
188
|
+
}
|
|
189
|
+
case 'gitlab': {
|
|
190
|
+
let match = /^https?:\/\/([^/?#]+)\/(.+?)\/-\/issues\/(\d+)/i.exec(text);
|
|
191
|
+
if (match) return { ref: `${match[2]}#${match[3]}`, data: { host: match[1], repo: match[2], number: Number(match[3]) } };
|
|
192
|
+
match = /^([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?(?:\/[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)+)#(\d+)$/.exec(text);
|
|
193
|
+
if (match) return { ref: `${match[1]}#${match[2]}`, data: { repo: match[1], number: Number(match[2]) } };
|
|
194
|
+
if (bare) {
|
|
195
|
+
const repo = context.repo;
|
|
196
|
+
if (typeof repo === 'string' && /^[^\s/]+(?:\/[^\s/]+)+$/.test(repo)) {
|
|
197
|
+
return { ref: `${repo}#${bare[1]}`, data: { repo, number: Number(bare[1]) } };
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
throw new TrackerError('bad-ref', `GitLab issues link as group/repo#N or a …/-/issues/N URL — got ${JSON.stringify(text.slice(0, 120))}.`, { provider });
|
|
201
|
+
}
|
|
202
|
+
case 'linear': {
|
|
203
|
+
let match = /^https?:\/\/linear\.app\/[^/?#]+\/issue\/([A-Za-z][A-Za-z0-9]*-\d+)/i.exec(text);
|
|
204
|
+
if (match) return { ref: match[1].toUpperCase(), data: { identifier: match[1].toUpperCase() } };
|
|
205
|
+
if (LINEAR_KEY.test(text)) return { ref: text.toUpperCase(), data: { identifier: text.toUpperCase() } };
|
|
206
|
+
throw new TrackerError('bad-ref', `Linear issues link as TEAM-123 or a linear.app/…/issue/TEAM-123 URL — got ${JSON.stringify(text.slice(0, 120))}.`, { provider });
|
|
207
|
+
}
|
|
208
|
+
case 'jira': {
|
|
209
|
+
let match = /^https?:\/\/[^/?#]+\/browse\/([A-Za-z][A-Za-z0-9_]*-\d+)/i.exec(text);
|
|
210
|
+
if (match) return { ref: match[1].toUpperCase(), data: { key: match[1].toUpperCase() } };
|
|
211
|
+
if (LINEAR_KEY.test(text)) return { ref: text.toUpperCase(), data: { key: text.toUpperCase() } };
|
|
212
|
+
throw new TrackerError('bad-ref', `Jira issues link as PROJ-123 or a <site>.atlassian.net/browse/PROJ-123 URL — got ${JSON.stringify(text.slice(0, 120))}.`, { provider });
|
|
213
|
+
}
|
|
214
|
+
default:
|
|
215
|
+
throw new TrackerError('unknown-provider', `No tracker provider ${JSON.stringify(provider)} (expected one of ${PROVIDER_IDS.join(', ')}).`, { provider });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ── Provider adapters ──────────────────────────────────────────────────────────────────────────────────
|
|
220
|
+
|
|
221
|
+
/** The CLI binary for a provider: PATH first, then well-known dirs, then a login-shell `command -v`. */
|
|
222
|
+
async function resolveTool(exec, env, tool) {
|
|
223
|
+
for (const dir of (env.PATH ?? '').split(delimiter).filter(Boolean)) {
|
|
224
|
+
const candidate = join(dir, tool);
|
|
225
|
+
if (existsSync(candidate)) return candidate;
|
|
226
|
+
}
|
|
227
|
+
for (const dir of TOOL_DIRS) {
|
|
228
|
+
const candidate = join(dir, tool);
|
|
229
|
+
if (existsSync(candidate)) return candidate;
|
|
230
|
+
}
|
|
231
|
+
// Login-shell probe, mirroring the Mac's RepoClone.toolPath: Homebrew/mise installs live outside the
|
|
232
|
+
// engine's inherited PATH. `/bin/zsh` on macOS, `/bin/sh` elsewhere; the probe is a fixed argv, never data.
|
|
233
|
+
for (const shell of process.platform === 'darwin' ? ['/bin/zsh', '/bin/sh'] : ['/bin/sh']) {
|
|
234
|
+
if (!existsSync(shell)) continue;
|
|
235
|
+
const probe = await exec(shell, ['-lc', `command -v ${tool}`], { timeoutMs: CLI_TIMEOUT_MS });
|
|
236
|
+
if (probe.code === 0) {
|
|
237
|
+
const found = probe.output.split('\n').map((line) => line.trim()).filter((line) => line.startsWith('/')).pop();
|
|
238
|
+
if (found) return found;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return undefined;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** `gh`'s "Logged in to github.com account <name>" line, or undefined — never the whole output (it may name tokens). */
|
|
245
|
+
function authAccount(output) {
|
|
246
|
+
const match = /account (\S+)|Logged in to \S+ as (\S+)/.exec(output);
|
|
247
|
+
return match?.[1] ?? match?.[2];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function requireTool(path, provider, tool) {
|
|
251
|
+
if (path === undefined) {
|
|
252
|
+
throw new TrackerError('provider-unconfigured', `${tool} is not installed — install it, then sign in.`, { provider, tool });
|
|
253
|
+
}
|
|
254
|
+
return path;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The gh adapter: `gh issue` argv calls. `exec(file, args, {cwd}) -> {code, output}` runs argv-only with
|
|
259
|
+
* prompt-killing env; a non-zero exit raises `tracker/provider-failed` with gh's own tail.
|
|
260
|
+
*/
|
|
261
|
+
const ghAdapter = {
|
|
262
|
+
id: 'github',
|
|
263
|
+
title: 'GitHub',
|
|
264
|
+
kind: 'cli',
|
|
265
|
+
tool: 'gh',
|
|
266
|
+
|
|
267
|
+
async probe(service) {
|
|
268
|
+
const cli = await service.tool('gh');
|
|
269
|
+
if (cli === undefined) return { id: 'github', title: 'GitHub', kind: 'cli', tool: 'gh', state: 'missing', detail: 'gh is not installed' };
|
|
270
|
+
const probe = await service.exec(cli, ['auth', 'status'], { timeoutMs: CLI_TIMEOUT_MS });
|
|
271
|
+
if (probe.code === 0) {
|
|
272
|
+
const account = authAccount(probe.output);
|
|
273
|
+
return { id: 'github', title: 'GitHub', kind: 'cli', tool: 'gh', state: 'ready', ...(account ? { detail: account } : {}) };
|
|
274
|
+
}
|
|
275
|
+
return { id: 'github', title: 'GitHub', kind: 'cli', tool: 'gh', state: 'signed-out', detail: 'gh auth login' };
|
|
276
|
+
},
|
|
277
|
+
|
|
278
|
+
async fetch(service, data) {
|
|
279
|
+
const cli = requireTool(await service.tool('gh'), 'github', 'gh');
|
|
280
|
+
const run = await service.exec(cli, ['issue', 'view', String(data.number), '--repo', data.repo, '--json', 'number,title,state,url'], { timeoutMs: HTTP_TIMEOUT_MS });
|
|
281
|
+
if (run.code !== 0) throw new TrackerError('provider-failed', errorTail(run.output) || `gh issue view exited ${run.code}`, { provider: 'github' });
|
|
282
|
+
let issue;
|
|
283
|
+
try { issue = JSON.parse(run.output); } catch { throw new TrackerError('provider-failed', 'gh issue view did not answer JSON.', { provider: 'github' }); }
|
|
284
|
+
const state = String(issue.state ?? '').toUpperCase() === 'CLOSED' ? 'done' : 'open';
|
|
285
|
+
return { url: issue.url, title: issue.title, state, stateLabel: state === 'done' ? 'Closed' : 'Open' };
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
async create(service, { title, body, cwd, repo }) {
|
|
289
|
+
const cli = requireTool(await service.tool('gh'), 'github', 'gh');
|
|
290
|
+
const args = ['issue', 'create', '--title', title, '--body', body ?? ''];
|
|
291
|
+
if (repo) args.push('--repo', repo);
|
|
292
|
+
const run = await service.exec(cli, args, { cwd, timeoutMs: ISSUE_TIMEOUT_MS });
|
|
293
|
+
const url = lastHttpURL(run.output, '/issues/');
|
|
294
|
+
if (run.code !== 0 || url === undefined) {
|
|
295
|
+
throw new TrackerError('provider-failed', errorTail(run.output) || `gh issue create exited ${run.code}`, { provider: 'github' });
|
|
296
|
+
}
|
|
297
|
+
const match = /github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/.exec(url);
|
|
298
|
+
const data = match ? { repo: match[1], number: Number(match[2]) } : { repo: repo ?? '', number: 0 };
|
|
299
|
+
if (data.number > 0) {
|
|
300
|
+
try {
|
|
301
|
+
const fetched = await this.fetch(service, data);
|
|
302
|
+
return { ...fetched, url: fetched.url ?? url, data };
|
|
303
|
+
} catch { /* the issue exists; the URL still links */ }
|
|
304
|
+
}
|
|
305
|
+
return { url, state: 'open', stateLabel: 'Open', data };
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/** The glab adapter: `glab issue`/`glab api` argv calls (JSON reads ride `glab api`). */
|
|
310
|
+
const glabAdapter = {
|
|
311
|
+
id: 'gitlab',
|
|
312
|
+
title: 'GitLab',
|
|
313
|
+
kind: 'cli',
|
|
314
|
+
tool: 'glab',
|
|
315
|
+
|
|
316
|
+
async probe(service) {
|
|
317
|
+
const cli = await service.tool('glab');
|
|
318
|
+
if (cli === undefined) return { id: 'gitlab', title: 'GitLab', kind: 'cli', tool: 'glab', state: 'missing', detail: 'glab is not installed' };
|
|
319
|
+
const probe = await service.exec(cli, ['auth', 'status'], { timeoutMs: CLI_TIMEOUT_MS });
|
|
320
|
+
if (probe.code === 0) {
|
|
321
|
+
const account = authAccount(probe.output);
|
|
322
|
+
return { id: 'gitlab', title: 'GitLab', kind: 'cli', tool: 'glab', state: 'ready', ...(account ? { detail: account } : {}) };
|
|
323
|
+
}
|
|
324
|
+
return { id: 'gitlab', title: 'GitLab', kind: 'cli', tool: 'glab', state: 'signed-out', detail: 'glab auth login' };
|
|
325
|
+
},
|
|
326
|
+
|
|
327
|
+
apiArgs(data, endpoint) {
|
|
328
|
+
const args = ['api', endpoint];
|
|
329
|
+
if (typeof data.host === 'string' && data.host && data.host !== 'gitlab.com' && data.host !== 'www.gitlab.com') {
|
|
330
|
+
args.push('--hostname', data.host);
|
|
331
|
+
}
|
|
332
|
+
return args;
|
|
333
|
+
},
|
|
334
|
+
|
|
335
|
+
async fetch(service, data) {
|
|
336
|
+
const cli = requireTool(await service.tool('glab'), 'gitlab', 'glab');
|
|
337
|
+
const endpoint = `projects/${encodeURIComponent(data.repo)}/issues/${data.number}`;
|
|
338
|
+
const run = await service.exec(cli, this.apiArgs(data, endpoint), { timeoutMs: HTTP_TIMEOUT_MS });
|
|
339
|
+
if (run.code !== 0) throw new TrackerError('provider-failed', errorTail(run.output) || `glab api exited ${run.code}`, { provider: 'gitlab' });
|
|
340
|
+
let issue;
|
|
341
|
+
try { issue = JSON.parse(run.output); } catch { throw new TrackerError('provider-failed', 'glab api did not answer JSON.', { provider: 'gitlab' }); }
|
|
342
|
+
const state = String(issue.state ?? '').toLowerCase() === 'closed' ? 'done' : 'open';
|
|
343
|
+
const host = data.host ?? 'gitlab.com';
|
|
344
|
+
return { url: issue.web_url ?? `https://${host}/${data.repo}/-/issues/${data.number}`, title: issue.title, state, stateLabel: state === 'done' ? 'Closed' : 'Open' };
|
|
345
|
+
},
|
|
346
|
+
|
|
347
|
+
async create(service, { title, body, cwd, repo }) {
|
|
348
|
+
const cli = requireTool(await service.tool('glab'), 'gitlab', 'glab');
|
|
349
|
+
const args = ['issue', 'create', '--title', title, '--description', body ?? '', '--yes'];
|
|
350
|
+
if (repo) args.push('--repo', repo);
|
|
351
|
+
const run = await service.exec(cli, args, { cwd, timeoutMs: ISSUE_TIMEOUT_MS });
|
|
352
|
+
const url = lastHttpURL(run.output, '/-/issues/');
|
|
353
|
+
if (run.code !== 0 || url === undefined) {
|
|
354
|
+
throw new TrackerError('provider-failed', errorTail(run.output) || `glab issue create exited ${run.code}`, { provider: 'gitlab' });
|
|
355
|
+
}
|
|
356
|
+
const match = /^https?:\/\/([^/]+)\/(.+?)\/-\/issues\/(\d+)/.exec(url);
|
|
357
|
+
const data = match ? { host: match[1], repo: match[2], number: Number(match[3]) } : { repo: repo ?? '', number: 0 };
|
|
358
|
+
if (data.number > 0) {
|
|
359
|
+
try {
|
|
360
|
+
const fetched = await this.fetch(service, data);
|
|
361
|
+
return { ...fetched, url: fetched.url ?? url, data };
|
|
362
|
+
} catch { /* the issue exists; the URL still links */ }
|
|
363
|
+
}
|
|
364
|
+
return { url, state: 'open', stateLabel: 'Open', data };
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
/** A Linear `state.type` → the normalized bucket (its `name` stays as `stateLabel`). */
|
|
369
|
+
function linearState(state) {
|
|
370
|
+
const type = String(state?.type ?? '').toLowerCase();
|
|
371
|
+
if (type === 'completed') return 'done';
|
|
372
|
+
if (type === 'canceled' || type === 'cancelled' || type === 'duplicate') return 'canceled';
|
|
373
|
+
return 'open';
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The Linear adapter: GraphQL over `fetch` — API key in the Authorization header, never logged. */
|
|
377
|
+
const linearAdapter = {
|
|
378
|
+
id: 'linear',
|
|
379
|
+
title: 'Linear',
|
|
380
|
+
kind: 'key',
|
|
381
|
+
|
|
382
|
+
config(service) {
|
|
383
|
+
const providers = service.providerConfig('linear') ?? {};
|
|
384
|
+
const apiKey = service.resolveSecret(providers.apiKey);
|
|
385
|
+
return { apiKey, team: typeof providers.team === 'string' ? providers.team.trim() : '', envRef: typeof providers.apiKey === 'string' && providers.apiKey.startsWith('env:') ? providers.apiKey.slice(4) : undefined };
|
|
386
|
+
},
|
|
387
|
+
|
|
388
|
+
requireKey(service) {
|
|
389
|
+
const config = this.config(service);
|
|
390
|
+
if (!config.apiKey) {
|
|
391
|
+
throw new TrackerError('provider-unconfigured', 'Linear needs an API key — set providers.linear.apiKey (env:LINEAR_API_KEY works) in the picasso-trackers entry.', { provider: 'linear' });
|
|
392
|
+
}
|
|
393
|
+
return config;
|
|
394
|
+
},
|
|
395
|
+
|
|
396
|
+
async probe(service) {
|
|
397
|
+
const config = this.config(service);
|
|
398
|
+
if (!config.apiKey) return { id: 'linear', title: 'Linear', kind: 'key', state: 'unconfigured', detail: 'needs an API key' };
|
|
399
|
+
const bits = [config.envRef ? `key from ${config.envRef}` : 'key configured'];
|
|
400
|
+
if (config.team) bits.push(`team ${config.team}`);
|
|
401
|
+
return { id: 'linear', title: 'Linear', kind: 'key', state: 'ready', detail: bits.join(' · ') };
|
|
402
|
+
},
|
|
403
|
+
|
|
404
|
+
/** One GraphQL call; a non-200 or an `errors` array raises `tracker/provider-failed` with Linear's own message. */
|
|
405
|
+
async query(service, config, query, variables) {
|
|
406
|
+
const { status, text } = await service.http('https://api.linear.app/graphql', {
|
|
407
|
+
method: 'POST',
|
|
408
|
+
headers: { 'Content-Type': 'application/json', Authorization: config.apiKey },
|
|
409
|
+
body: JSON.stringify({ query, variables }),
|
|
410
|
+
timeoutMs: HTTP_TIMEOUT_MS,
|
|
411
|
+
});
|
|
412
|
+
let document;
|
|
413
|
+
try { document = JSON.parse(text); } catch { document = undefined; }
|
|
414
|
+
const message = Array.isArray(document?.errors) && document.errors.length > 0 ? document.errors[0]?.message : undefined;
|
|
415
|
+
if (message) throw new TrackerError('provider-failed', String(message), { provider: 'linear' });
|
|
416
|
+
if (status !== 200 || !isRecord(document?.data)) {
|
|
417
|
+
throw new TrackerError('provider-failed', `Linear answered HTTP ${status || 'error'}: ${errorTail(text, 300) || 'empty response'}`, { provider: 'linear' });
|
|
418
|
+
}
|
|
419
|
+
return document.data;
|
|
420
|
+
},
|
|
421
|
+
|
|
422
|
+
async fetch(service, data) {
|
|
423
|
+
const config = this.requireKey(service);
|
|
424
|
+
const answer = await this.query(service, config, 'query($id: String!) { issue(id: $id) { identifier title url state { name type } } }', { id: data.identifier });
|
|
425
|
+
const issue = answer.issue;
|
|
426
|
+
if (!isRecord(issue)) throw new TrackerError('provider-failed', `Linear has no issue ${data.identifier}.`, { provider: 'linear' });
|
|
427
|
+
const state = linearState(issue.state);
|
|
428
|
+
return { url: issue.url, title: issue.title, state, stateLabel: issue.state?.name ?? state };
|
|
429
|
+
},
|
|
430
|
+
|
|
431
|
+
async teamId(service, config) {
|
|
432
|
+
const team = config.team;
|
|
433
|
+
if (!team) {
|
|
434
|
+
throw new TrackerError('provider-unconfigured', 'Creating Linear issues needs a team — set providers.linear.team (a key like ENG, or a team id).', { provider: 'linear' });
|
|
435
|
+
}
|
|
436
|
+
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(team)) return team;
|
|
437
|
+
const answer = await this.query(service, config, 'query($key: String!) { teams(filter: { key: { eq: $key } }) { nodes { id } } }', { key: team });
|
|
438
|
+
const id = answer.teams?.nodes?.[0]?.id;
|
|
439
|
+
if (typeof id !== 'string' || !id) throw new TrackerError('provider-failed', `Linear has no team ${JSON.stringify(team)}.`, { provider: 'linear' });
|
|
440
|
+
return id;
|
|
441
|
+
},
|
|
442
|
+
|
|
443
|
+
async create(service, { title, body }) {
|
|
444
|
+
const config = this.requireKey(service);
|
|
445
|
+
const teamId = await this.teamId(service, config);
|
|
446
|
+
const answer = await this.query(service, config, 'mutation($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { identifier title url state { name type } } } }', {
|
|
447
|
+
input: { title, ...(body ? { description: body } : {}), teamId },
|
|
448
|
+
});
|
|
449
|
+
const issue = answer.issueCreate?.issue;
|
|
450
|
+
if (answer.issueCreate?.success !== true || !isRecord(issue)) {
|
|
451
|
+
throw new TrackerError('provider-failed', 'Linear declined the issue without an error detail.', { provider: 'linear' });
|
|
452
|
+
}
|
|
453
|
+
const state = linearState(issue.state);
|
|
454
|
+
return { url: issue.url, title: issue.title, state, stateLabel: issue.state?.name ?? state, data: { identifier: issue.identifier } };
|
|
455
|
+
},
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
/** The Jira adapter: REST v3 with basic auth — `email` + `token` (or env refs) from plugin config. */
|
|
459
|
+
const jiraAdapter = {
|
|
460
|
+
id: 'jira',
|
|
461
|
+
title: 'Jira',
|
|
462
|
+
kind: 'key',
|
|
463
|
+
|
|
464
|
+
config(service) {
|
|
465
|
+
const providers = service.providerConfig('jira') ?? {};
|
|
466
|
+
const baseUrl = typeof providers.baseUrl === 'string' ? providers.baseUrl.trim().replace(/\/+$/, '') : '';
|
|
467
|
+
const token = service.resolveSecret(providers.token);
|
|
468
|
+
const email = typeof providers.email === 'string' ? providers.email.trim() : '';
|
|
469
|
+
const project = typeof providers.project === 'string' ? providers.project.trim() : '';
|
|
470
|
+
const envRef = typeof providers.token === 'string' && providers.token.startsWith('env:') ? providers.token.slice(4) : undefined;
|
|
471
|
+
return { baseUrl, token, email, project, envRef };
|
|
472
|
+
},
|
|
473
|
+
|
|
474
|
+
requireConfig(service) {
|
|
475
|
+
const config = this.config(service);
|
|
476
|
+
const missing = [config.baseUrl ? '' : 'baseUrl', config.email ? '' : 'email', config.token ? '' : 'token'].filter(Boolean);
|
|
477
|
+
if (missing.length > 0) {
|
|
478
|
+
throw new TrackerError('provider-unconfigured', `Jira needs providers.jira.${missing.join(' and providers.jira.')} in the picasso-trackers entry (the token may be env:JIRA_API_TOKEN).`, { provider: 'jira' });
|
|
479
|
+
}
|
|
480
|
+
if (!/^https:\/\//.test(config.baseUrl)) {
|
|
481
|
+
throw new TrackerError('provider-unconfigured', 'Jira baseUrl must be an https:// URL (e.g. https://yoursite.atlassian.net).', { provider: 'jira' });
|
|
482
|
+
}
|
|
483
|
+
return config;
|
|
484
|
+
},
|
|
485
|
+
|
|
486
|
+
async probe(service) {
|
|
487
|
+
const config = this.config(service);
|
|
488
|
+
const missing = [config.baseUrl ? '' : 'site', config.email ? '' : 'email', config.token ? '' : 'token'].filter(Boolean);
|
|
489
|
+
if (missing.length > 0) return { id: 'jira', title: 'Jira', kind: 'key', state: 'unconfigured', detail: `needs ${missing.join(', ')}` };
|
|
490
|
+
const host = /^https?:\/\/([^/]+)/.exec(config.baseUrl)?.[1];
|
|
491
|
+
const bits = [host ?? 'configured', config.envRef ? `token from ${config.envRef}` : 'token configured'];
|
|
492
|
+
if (config.project) bits.push(`project ${config.project}`);
|
|
493
|
+
return { id: 'jira', title: 'Jira', kind: 'key', state: 'ready', detail: bits.join(' · ') };
|
|
494
|
+
},
|
|
495
|
+
|
|
496
|
+
headers(config, extra = {}) {
|
|
497
|
+
return {
|
|
498
|
+
Accept: 'application/json',
|
|
499
|
+
Authorization: `Basic ${Buffer.from(`${config.email}:${config.token}`).toString('base64')}`,
|
|
500
|
+
...extra,
|
|
501
|
+
};
|
|
502
|
+
},
|
|
503
|
+
|
|
504
|
+
/** `GET …/issue/<key>?fields=summary,status` → the normalized face; Jira's own message rides the error. */
|
|
505
|
+
async fetch(service, data) {
|
|
506
|
+
const config = this.requireConfig(service);
|
|
507
|
+
const { status, text } = await service.http(`${config.baseUrl}/rest/api/3/issue/${encodeURIComponent(data.key)}?fields=summary,status`, {
|
|
508
|
+
headers: this.headers(config),
|
|
509
|
+
timeoutMs: HTTP_TIMEOUT_MS,
|
|
510
|
+
});
|
|
511
|
+
if (status !== 200) {
|
|
512
|
+
throw new TrackerError('provider-failed', `Jira answered HTTP ${status || 'error'}: ${errorTail(text, 300) || 'empty response'}`, { provider: 'jira' });
|
|
513
|
+
}
|
|
514
|
+
let issue;
|
|
515
|
+
try { issue = JSON.parse(text); } catch { throw new TrackerError('provider-failed', 'Jira did not answer JSON.', { provider: 'jira' }); }
|
|
516
|
+
const statusCategory = String(issue.fields?.status?.statusCategory?.key ?? '').toLowerCase();
|
|
517
|
+
const state = statusCategory === 'done' ? 'done' : 'open';
|
|
518
|
+
return { url: `${config.baseUrl}/browse/${data.key}`, title: issue.fields?.summary, state, stateLabel: issue.fields?.status?.name ?? state };
|
|
519
|
+
},
|
|
520
|
+
|
|
521
|
+
async create(service, { title, body }) {
|
|
522
|
+
const config = this.requireConfig(service);
|
|
523
|
+
if (!config.project) {
|
|
524
|
+
throw new TrackerError('provider-unconfigured', 'Creating Jira issues needs a project — set providers.jira.project (a key like PROJ).', { provider: 'jira' });
|
|
525
|
+
}
|
|
526
|
+
const description = {
|
|
527
|
+
type: 'doc', version: 1,
|
|
528
|
+
content: [{ type: 'paragraph', content: [{ type: 'text', text: body ?? '' }] }],
|
|
529
|
+
};
|
|
530
|
+
const { status, text } = await service.http(`${config.baseUrl}/rest/api/3/issue`, {
|
|
531
|
+
method: 'POST',
|
|
532
|
+
headers: this.headers(config, { 'Content-Type': 'application/json' }),
|
|
533
|
+
body: JSON.stringify({ fields: { project: { key: config.project }, summary: title, description, issuetype: { name: 'Task' } } }),
|
|
534
|
+
timeoutMs: ISSUE_TIMEOUT_MS,
|
|
535
|
+
});
|
|
536
|
+
if (status !== 200 && status !== 201) {
|
|
537
|
+
throw new TrackerError('provider-failed', `Jira answered HTTP ${status || 'error'}: ${errorTail(text, 300) || 'empty response'}`, { provider: 'jira' });
|
|
538
|
+
}
|
|
539
|
+
let created;
|
|
540
|
+
try { created = JSON.parse(text); } catch { created = undefined; }
|
|
541
|
+
const key = typeof created?.key === 'string' && created.key ? created.key : undefined;
|
|
542
|
+
if (key === undefined) throw new TrackerError('provider-failed', 'Jira created no issue key.', { provider: 'jira' });
|
|
543
|
+
const data = { key };
|
|
544
|
+
try {
|
|
545
|
+
const fetched = await this.fetch(service, data);
|
|
546
|
+
return { ...fetched, url: `${config.baseUrl}/browse/${key}`, data };
|
|
547
|
+
} catch {
|
|
548
|
+
return { url: `${config.baseUrl}/browse/${key}`, title, state: 'open', stateLabel: 'Open', data };
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
export const ADAPTERS = { github: ghAdapter, gitlab: glabAdapter, linear: linearAdapter, jira: jiraAdapter };
|
|
554
|
+
|
|
555
|
+
// ── The registry (Remote surface + sidecar) ─────────────────────────────────────────────────────────────
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* The tracker link registry. `dataDir` is the dsh data directory (the sidecar's parent); `providers` is a
|
|
559
|
+
* thunk so a volatile config ref is re-read on every call; `exec`/`http`/`env`/`toolResolver` inject for
|
|
560
|
+
* tests. Every mutation is serialized and the sidecar is replaced atomically.
|
|
561
|
+
*/
|
|
562
|
+
export class TrackerRegistry {
|
|
563
|
+
constructor(options) {
|
|
564
|
+
this.dataDir = resolve(options.dataDir);
|
|
565
|
+
this.sidecar = join(this.dataDir, SIDECAR_FILENAME);
|
|
566
|
+
this.now = options.now ?? Date.now;
|
|
567
|
+
this.exec = options.exec ?? ((file, args, opts = {}) => execArgv(file, args, { ...opts, env: opts.env ?? cliEnv(this.env) }));
|
|
568
|
+
this.http = options.http ?? httpRequest;
|
|
569
|
+
this.env = options.env ?? process.env;
|
|
570
|
+
this.providerConfigSource = typeof options.providers === 'function' ? options.providers : () => options.providers ?? {};
|
|
571
|
+
this.toolResolver = options.toolResolver ?? resolveTool;
|
|
572
|
+
this.adapters = options.adapters ?? ADAPTERS;
|
|
573
|
+
this.toolCache = new Map();
|
|
574
|
+
this.tail = Promise.resolve();
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// ── Remote surface (`tracker/<method>`; wire args are the parameter names) ────────────────────────────
|
|
578
|
+
|
|
579
|
+
/** Provider readiness for `GET /trackers`: all four rows, `state` + a safe one-line `detail`. */
|
|
580
|
+
async providers() {
|
|
581
|
+
const rows = await Promise.all(PROVIDER_IDS.map((id) => this.adapters[id].probe(this).catch((error) => ({
|
|
582
|
+
id, title: this.adapters[id].title, kind: this.adapters[id].kind ?? 'key', state: 'unconfigured',
|
|
583
|
+
detail: String(error?.message ?? error).slice(0, 160),
|
|
584
|
+
}))));
|
|
585
|
+
return { providers: rows };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Attach `ref` on `provider` to `sessionId`. The provider's own lookup runs first so a bad ref answers
|
|
590
|
+
* with the provider's own error text (`tracker/provider-failed`), not a generic failure.
|
|
591
|
+
*/
|
|
592
|
+
link(sessionId, provider, ref, _cwd) {
|
|
593
|
+
return this.serial(async () => {
|
|
594
|
+
const id = requireId(sessionId);
|
|
595
|
+
const adapter = this.adapterFor(provider);
|
|
596
|
+
const parsed = parseRef(provider, ref, { repo: this.configuredRepo(provider) });
|
|
597
|
+
const fetched = await adapter.fetch(this, parsed.data);
|
|
598
|
+
const state = this.read();
|
|
599
|
+
const entry = this.entry(id, provider, parsed, fetched);
|
|
600
|
+
state.links[id] = entry;
|
|
601
|
+
await this.write(state);
|
|
602
|
+
return { linked: true, ...entry };
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
unlink(sessionId) {
|
|
607
|
+
return this.serial(async () => {
|
|
608
|
+
const id = requireId(sessionId);
|
|
609
|
+
const state = this.read();
|
|
610
|
+
const was = id in state.links;
|
|
611
|
+
delete state.links[id];
|
|
612
|
+
if (was) await this.write(state);
|
|
613
|
+
return { sessionId: id, linked: false };
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Files an issue on the provider and links it to the thread in the same serialized step. */
|
|
618
|
+
create(sessionId, provider, title, body, cwd, repo) {
|
|
619
|
+
return this.serial(async () => {
|
|
620
|
+
const id = requireId(sessionId);
|
|
621
|
+
const adapter = this.adapterFor(provider);
|
|
622
|
+
const headline = requireTitle(title);
|
|
623
|
+
const target = requireTarget(provider, { cwd, repo: repo ?? this.configuredRepo(provider) });
|
|
624
|
+
const created = await adapter.create(this, { title: headline, body: typeof body === 'string' ? body : '', ...target });
|
|
625
|
+
const state = this.read();
|
|
626
|
+
const display = created.data ? displayRef(provider, created.data) : '';
|
|
627
|
+
const entry = this.entry(id, provider, { ref: display || created.url, data: created.data ?? {} }, created);
|
|
628
|
+
state.links[id] = entry;
|
|
629
|
+
await this.write(state);
|
|
630
|
+
return { linked: true, ...entry };
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* The thread's link plus a fresh provider read. A refresh failure returns the stored entry marked
|
|
636
|
+
* `stale` with the provider's message in `error` — the chip keeps its last-known state.
|
|
637
|
+
*/
|
|
638
|
+
status(sessionId) {
|
|
639
|
+
return this.serial(async () => {
|
|
640
|
+
const id = requireId(sessionId);
|
|
641
|
+
const state = this.read();
|
|
642
|
+
const entry = state.links[id];
|
|
643
|
+
if (entry === undefined) return { linked: false, sessionId: id };
|
|
644
|
+
try {
|
|
645
|
+
const adapter = this.adapterFor(entry.provider);
|
|
646
|
+
const fetched = await adapter.fetch(this, entry.data ?? {});
|
|
647
|
+
const next = { ...entry, ...fetched, checkedAt: this.now() };
|
|
648
|
+
state.links[id] = next;
|
|
649
|
+
await this.write(state);
|
|
650
|
+
return { linked: true, ...next };
|
|
651
|
+
} catch (error) {
|
|
652
|
+
return {
|
|
653
|
+
linked: true, ...entry,
|
|
654
|
+
stale: true,
|
|
655
|
+
error: error instanceof TrackerError || typeof error?.message === 'string' ? String(error.message) : String(error),
|
|
656
|
+
...(error?.code ? { code: error.code } : {}),
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
list() {
|
|
663
|
+
return this.serial(async () => {
|
|
664
|
+
const state = this.read();
|
|
665
|
+
return { links: state.links };
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// ── Internals ─────────────────────────────────────────────────────────────────────────────────────────
|
|
670
|
+
|
|
671
|
+
adapterFor(provider) {
|
|
672
|
+
const adapter = typeof provider === 'string' ? this.adapters[provider] : undefined;
|
|
673
|
+
if (adapter === undefined) {
|
|
674
|
+
throw new TrackerError('unknown-provider', `No tracker provider ${JSON.stringify(provider)} (expected one of ${PROVIDER_IDS.join(', ')}).`, { provider });
|
|
675
|
+
}
|
|
676
|
+
return adapter;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** `providers.<id>` from the (possibly volatile) plugin config. */
|
|
680
|
+
providerConfig(provider) {
|
|
681
|
+
const providers = this.providerConfigSource();
|
|
682
|
+
const entry = isRecord(providers) ? providers[provider] : undefined;
|
|
683
|
+
return isRecord(entry) ? entry : undefined;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
configuredRepo(provider) {
|
|
687
|
+
const repo = this.providerConfig(provider)?.repo;
|
|
688
|
+
return typeof repo === 'string' && repo.trim() ? repo.trim() : undefined;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Resolve a stored credential: `env:NAME` reads the engine's environment at call time (preferred — no
|
|
693
|
+
* raw token persisted); anything else is used verbatim. Returns `undefined` for missing values.
|
|
694
|
+
*/
|
|
695
|
+
resolveSecret(value) {
|
|
696
|
+
if (typeof value !== 'string' || value.length === 0) return undefined;
|
|
697
|
+
if (value.startsWith('env:')) {
|
|
698
|
+
const name = value.slice(4);
|
|
699
|
+
const resolved = this.env[name];
|
|
700
|
+
return typeof resolved === 'string' && resolved ? resolved : undefined;
|
|
701
|
+
}
|
|
702
|
+
return value;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
async tool(name) {
|
|
706
|
+
if (!this.toolCache.has(name)) this.toolCache.set(name, await this.toolResolver(this.exec, this.env, name));
|
|
707
|
+
return this.toolCache.get(name);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
entry(sessionId, provider, parsed, fetched) {
|
|
711
|
+
const at = this.now();
|
|
712
|
+
return {
|
|
713
|
+
provider,
|
|
714
|
+
ref: parsed.ref,
|
|
715
|
+
url: fetched.url ?? '',
|
|
716
|
+
...(typeof fetched.title === 'string' && fetched.title ? { title: fetched.title } : {}),
|
|
717
|
+
state: fetched.state ?? 'open',
|
|
718
|
+
...(typeof fetched.stateLabel === 'string' && fetched.stateLabel ? { stateLabel: fetched.stateLabel } : {}),
|
|
719
|
+
linkedAt: at,
|
|
720
|
+
checkedAt: at,
|
|
721
|
+
data: parsed.data,
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
read() {
|
|
726
|
+
try {
|
|
727
|
+
const parsed = JSON.parse(readFileSync(this.sidecar, 'utf8'));
|
|
728
|
+
if (!isRecord(parsed)) return emptyState();
|
|
729
|
+
const links = {};
|
|
730
|
+
for (const [id, entry] of Object.entries(isRecord(parsed.links) ? parsed.links : {})) {
|
|
731
|
+
if (isRecord(entry) && typeof entry.provider === 'string' && typeof entry.ref === 'string') links[id] = entry;
|
|
732
|
+
}
|
|
733
|
+
return { version: 1, links };
|
|
734
|
+
} catch {
|
|
735
|
+
return emptyState();
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
async write(state) {
|
|
740
|
+
await mkdir(this.dataDir, { recursive: true });
|
|
741
|
+
const temporary = `${this.sidecar}.${process.pid}.tmp`;
|
|
742
|
+
await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
743
|
+
await rename(temporary, this.sidecar);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
serial(body) {
|
|
747
|
+
const run = this.tail.then(body, body);
|
|
748
|
+
this.tail = run.catch(() => undefined);
|
|
749
|
+
return run;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const REMOTE_METHODS = ['providers', 'link', 'unlink', 'create', 'status', 'list'];
|
|
754
|
+
|
|
755
|
+
/** The gateway's source-mode Remote markers, as `@Remote()` would write them on the class prototype. */
|
|
756
|
+
Object.defineProperty(TrackerRegistry.prototype, REMOTE_METHOD_DESCRIPTOR, {
|
|
757
|
+
configurable: true,
|
|
758
|
+
value: Object.freeze({ version: 1, methods: Object.freeze(REMOTE_METHODS.map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))) }),
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
function requireId(sessionId) {
|
|
762
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 512) {
|
|
763
|
+
throw new TrackerError('bad-request', 'sessionId must be a non-empty string.');
|
|
764
|
+
}
|
|
765
|
+
return sessionId;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function requireTitle(title) {
|
|
769
|
+
const text = typeof title === 'string' ? title.trim() : '';
|
|
770
|
+
if (!text || text.length > 512) throw new TrackerError('bad-request', 'issue create needs a non-empty title.');
|
|
771
|
+
return text;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** gh/glab need a `-R` target or a cwd inside the checkout; the REST providers need neither. */
|
|
775
|
+
function requireTarget(provider, { cwd, repo }) {
|
|
776
|
+
if (provider === 'github' || provider === 'gitlab') {
|
|
777
|
+
const dir = typeof cwd === 'string' && cwd.startsWith('/') ? cwd : undefined;
|
|
778
|
+
const target = typeof repo === 'string' && repo.trim() ? repo.trim() : undefined;
|
|
779
|
+
if (target === undefined && dir === undefined) {
|
|
780
|
+
throw new TrackerError('repo-required', `Creating a ${provider === 'github' ? 'GitHub' : 'GitLab'} issue needs a repo (owner/repo) or the thread's folder.`, { provider });
|
|
781
|
+
}
|
|
782
|
+
return { repo: target, cwd: dir };
|
|
783
|
+
}
|
|
784
|
+
return { cwd: typeof cwd === 'string' && cwd.startsWith('/') ? cwd : undefined };
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** The canonical display ref for a create answer (the link's stored `ref`). */
|
|
788
|
+
function displayRef(provider, data) {
|
|
789
|
+
switch (provider) {
|
|
790
|
+
case 'github':
|
|
791
|
+
case 'gitlab': return data.repo && data.number ? `${data.repo}#${data.number}` : '';
|
|
792
|
+
case 'linear': return data.identifier ?? '';
|
|
793
|
+
case 'jira': return data.key ?? '';
|
|
794
|
+
default: return '';
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/** A volatile config ref (`{get,set,[write]}`) unwraps to its snapshot; plain values pass through. */
|
|
799
|
+
function unref(value) {
|
|
800
|
+
return isRecord(value) && typeof value.get === 'function' && typeof value.set === 'function' ? value.get() : value;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** The dsh data directory: the parent of config `root` (dshHomePath('sessions')), else `$DSH_HOME`, else `~/.dsh`. */
|
|
804
|
+
export function dataDirFor(config) {
|
|
805
|
+
if (isRecord(config) && typeof config.root === 'string' && config.root) return dirname(config.root);
|
|
806
|
+
return process.env.DSH_HOME || join(homedir(), '.dsh');
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// ── Config schema (settings/mutate on the `picasso-trackers` entry) ────────────────────────────────────
|
|
810
|
+
|
|
811
|
+
/**
|
|
812
|
+
* `@deepseek-ai/schemastery` from the dsh install that hosts this plugin — the same trick
|
|
813
|
+
* @picasso/auth-bridge uses for `dsh-authorization`, but synchronous: the Host's own argv[1] (the launched
|
|
814
|
+
* dsh bin) anchors `createRequire`, with `dsh` on PATH as the runner-up. `undefined` outside a dsh Host —
|
|
815
|
+
* the plugin then runs schema-less (config passes through raw and `settings/mutate` declines).
|
|
816
|
+
*/
|
|
817
|
+
function loadSchemastery() {
|
|
818
|
+
const anchors = [];
|
|
819
|
+
if (typeof process.argv?.[1] === 'string' && process.argv[1]) anchors.push(process.argv[1]);
|
|
820
|
+
for (const dir of (process.env.PATH ?? '').split(delimiter).filter(Boolean)) anchors.push(join(dir, 'dsh'));
|
|
821
|
+
for (const anchor of anchors) {
|
|
822
|
+
try {
|
|
823
|
+
const require = createRequire(realpathSync(anchor));
|
|
824
|
+
const mod = require(require.resolve('@deepseek-ai/schemastery'));
|
|
825
|
+
const z = mod?.default ?? mod;
|
|
826
|
+
if (typeof z?.object === 'function') return z;
|
|
827
|
+
} catch {
|
|
828
|
+
// not a dsh install — try the next anchor
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return undefined;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function buildConfig(z) {
|
|
835
|
+
return z.object({
|
|
836
|
+
/** The sessions root (`dshHomePath('sessions')`); the sidecar lands in its parent (the dsh data dir). */
|
|
837
|
+
root: z.string().default(''),
|
|
838
|
+
/** Provider settings, live-editable through `settings/mutate` — secrets as `env:VAR` or `role('secret')`. */
|
|
839
|
+
providers: z.object({
|
|
840
|
+
github: z.object({
|
|
841
|
+
/** Default `-R` target for `owner/repo` refs and `create` when no repo arg/cwd is given. */
|
|
842
|
+
repo: z.string().default(''),
|
|
843
|
+
}).default({}),
|
|
844
|
+
gitlab: z.object({
|
|
845
|
+
repo: z.string().default(''),
|
|
846
|
+
/** Self-hosted GitLab host for `glab api --hostname` reads; gitlab.com when empty. */
|
|
847
|
+
host: z.string().default(''),
|
|
848
|
+
}).default({}),
|
|
849
|
+
linear: z.object({
|
|
850
|
+
/** API key — `env:LINEAR_API_KEY` preferred so nothing secret persists; `role('secret')` redacts it. */
|
|
851
|
+
apiKey: z.string().role('secret').default(''),
|
|
852
|
+
/** Team key (`ENG`) or id — required for `create`, optional for link/status. */
|
|
853
|
+
team: z.string().default(''),
|
|
854
|
+
}).default({}),
|
|
855
|
+
jira: z.object({
|
|
856
|
+
/** e.g. https://yoursite.atlassian.net */
|
|
857
|
+
baseUrl: z.string().default(''),
|
|
858
|
+
email: z.string().default(''),
|
|
859
|
+
/** API token — `env:JIRA_API_TOKEN` preferred; `role('secret')` redacts it. */
|
|
860
|
+
token: z.string().role('secret').default(''),
|
|
861
|
+
/** Project key for `create` (e.g. PROJ). */
|
|
862
|
+
project: z.string().default(''),
|
|
863
|
+
}).default({}),
|
|
864
|
+
}).volatile().default({}),
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
const schemastery = loadSchemastery();
|
|
869
|
+
/**
|
|
870
|
+
* The settings schema for this entry's ns (`picasso-trackers`): `providers` is the only live field, so a
|
|
871
|
+
* `settings/mutate` writes `{op:'set', path:['providers', <id>, <field>], value}` into the profile and the
|
|
872
|
+
* running fiber's volatile ref at once. `undefined` when no bundled schemastery resolves, or when the
|
|
873
|
+
* resolved build can't express this schema — either way the plugin still runs and `settings/mutate`
|
|
874
|
+
* simply declines, matching the schema-less sibling plugins.
|
|
875
|
+
*/
|
|
876
|
+
export let Config = (() => {
|
|
877
|
+
try {
|
|
878
|
+
return schemastery === undefined ? undefined : buildConfig(schemastery);
|
|
879
|
+
} catch {
|
|
880
|
+
return undefined;
|
|
881
|
+
}
|
|
882
|
+
})();
|
|
883
|
+
|
|
884
|
+
/** Cordis entry. Provides `tracker`, bound for the Typert gateway under its own name. */
|
|
885
|
+
export function apply(ctx, config) {
|
|
886
|
+
const service = new TrackerRegistry({
|
|
887
|
+
dataDir: dataDirFor(config),
|
|
888
|
+
// `config.providers` may be a volatile ref after schema parsing — read it through the thunk so
|
|
889
|
+
// `settings/mutate` commits are visible on the next call without a restart.
|
|
890
|
+
providers: () => unref(config?.providers) ?? {},
|
|
891
|
+
env: process.env,
|
|
892
|
+
});
|
|
893
|
+
service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
|
|
894
|
+
ctx.provide(SERVICE_KEY, service);
|
|
895
|
+
}
|