t3code-session-manager 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +21 -0
- package/.claude-plugin/plugin.json +19 -0
- package/CHANGELOG.md +149 -0
- package/LICENSE +21 -0
- package/README.md +661 -2
- package/README.pt.md +617 -0
- package/bin/entry.d.mts +2 -0
- package/bin/entry.mjs +19 -0
- package/bin/t3sm.mjs +44 -0
- package/commands/import.md +30 -0
- package/commands/organize.md +36 -0
- package/commands/status.md +24 -0
- package/commands/sync.md +26 -0
- package/dist/apply/apply.js +993 -0
- package/dist/apply/claudeWriter.js +168 -0
- package/dist/apply/copyTranscript.js +116 -0
- package/dist/apply/importer.js +697 -0
- package/dist/apply/materialize.js +335 -0
- package/dist/apply/waves.js +108 -0
- package/dist/assistant/core.js +295 -0
- package/dist/assistant/deps.js +256 -0
- package/dist/assistant/i18n.js +38 -0
- package/dist/assistant/messages.en.js +494 -0
- package/dist/assistant/messages.pt.js +495 -0
- package/dist/assistant/runner.js +64 -0
- package/dist/assistant/steps.js +1362 -0
- package/dist/build.json +1 -0
- package/dist/cli/applyScreen.js +158 -0
- package/dist/cli/commands/accounts.js +254 -0
- package/dist/cli/commands/apply.js +199 -0
- package/dist/cli/commands/changelog.js +61 -0
- package/dist/cli/commands/doctor.js +105 -0
- package/dist/cli/commands/help.js +158 -0
- package/dist/cli/commands/merge.js +224 -0
- package/dist/cli/commands/organize.js +872 -0
- package/dist/cli/commands/plan.js +161 -0
- package/dist/cli/commands/projects.js +430 -0
- package/dist/cli/commands/quarantine.js +203 -0
- package/dist/cli/commands/recover.js +230 -0
- package/dist/cli/commands/rollback.js +281 -0
- package/dist/cli/commands/scan.js +117 -0
- package/dist/cli/commands/schedule.js +288 -0
- package/dist/cli/commands/start.js +45 -0
- package/dist/cli/commands/status.js +615 -0
- package/dist/cli/commands/sync.js +336 -0
- package/dist/cli/commands/update.js +398 -0
- package/dist/cli/errors.js +53 -0
- package/dist/cli/failures.js +91 -0
- package/dist/cli/flags.js +53 -0
- package/dist/cli/help.en.js +549 -0
- package/dist/cli/help.pt.js +566 -0
- package/dist/cli/helpText.js +211 -0
- package/dist/cli/helpTopics.js +58 -0
- package/dist/cli/locked.js +12 -0
- package/dist/cli/main.js +155 -0
- package/dist/cli/screen.js +3 -0
- package/dist/cli/ui.js +111 -0
- package/dist/cli/words.js +2 -0
- package/dist/core/activity.js +16 -0
- package/dist/core/changelog.js +47 -0
- package/dist/core/config.js +530 -0
- package/dist/core/fsutil.js +171 -0
- package/dist/core/glob.js +34 -0
- package/dist/core/history.js +32 -0
- package/dist/core/journal.js +274 -0
- package/dist/core/lock.js +337 -0
- package/dist/core/mask.js +31 -0
- package/dist/core/paths.js +68 -0
- package/dist/core/pid.js +101 -0
- package/dist/core/run.js +4 -0
- package/dist/core/semver.js +18 -0
- package/dist/core/sysroot.js +29 -0
- package/dist/core/types.js +229 -0
- package/dist/core/uuid.js +29 -0
- package/dist/core/version.js +72 -0
- package/dist/help/convert.md +20 -0
- package/dist/help/convert.pt.md +21 -0
- package/dist/help/cwd-unreadable.md +22 -0
- package/dist/help/cwd-unreadable.pt.md +22 -0
- package/dist/help/decisions.md +20 -0
- package/dist/help/decisions.pt.md +20 -0
- package/dist/help/errors.md +20 -0
- package/dist/help/errors.pt.md +22 -0
- package/dist/help/held.md +20 -0
- package/dist/help/held.pt.md +20 -0
- package/dist/help/history.md +27 -0
- package/dist/help/history.pt.md +29 -0
- package/dist/help/instance-unavailable.md +18 -0
- package/dist/help/instance-unavailable.pt.md +19 -0
- package/dist/help/not-imported.md +19 -0
- package/dist/help/not-imported.pt.md +19 -0
- package/dist/help/orphaned.md +19 -0
- package/dist/help/orphaned.pt.md +19 -0
- package/dist/help/project-mismatch.md +15 -0
- package/dist/help/project-mismatch.pt.md +15 -0
- package/dist/help/t3-native.md +22 -0
- package/dist/help/t3-native.pt.md +22 -0
- package/dist/help/updates.md +26 -0
- package/dist/help/updates.pt.md +28 -0
- package/dist/help/watcher.md +24 -0
- package/dist/help/watcher.pt.md +25 -0
- package/dist/i18n/cli.js +41 -0
- package/dist/i18n/lang.js +55 -0
- package/dist/i18n/messages.en.js +1140 -0
- package/dist/i18n/messages.pt.js +1149 -0
- package/dist/i18n/words.js +12 -0
- package/dist/ops/accounts.js +170 -0
- package/dist/ops/autoUpdate.js +223 -0
- package/dist/ops/discoverAccounts.js +343 -0
- package/dist/ops/doctor.js +811 -0
- package/dist/ops/elevated.js +47 -0
- package/dist/ops/errorCodes.js +39 -0
- package/dist/ops/follow.js +558 -0
- package/dist/ops/merge.js +830 -0
- package/dist/ops/notify.js +249 -0
- package/dist/ops/plugin.js +92 -0
- package/dist/ops/projects.js +113 -0
- package/dist/ops/quarantine.js +415 -0
- package/dist/ops/rollback.js +868 -0
- package/dist/ops/schedule.js +464 -0
- package/dist/ops/successor.js +51 -0
- package/dist/ops/sync.js +859 -0
- package/dist/ops/syncStatus.js +290 -0
- package/dist/ops/update.js +273 -0
- package/dist/ops/updater.js +641 -0
- package/dist/ops/watch.js +676 -0
- package/dist/ops/watcherControl.js +212 -0
- package/dist/ops/watcherHealth.js +75 -0
- package/dist/organize/apply.js +495 -0
- package/dist/organize/history.js +192 -0
- package/dist/organize/plan.js +283 -0
- package/dist/organize/rename.js +58 -0
- package/dist/organize/sessions.js +100 -0
- package/dist/organize/titles.js +70 -0
- package/dist/organize/types.js +73 -0
- package/dist/plan/categories.js +104 -0
- package/dist/plan/dedupe.js +137 -0
- package/dist/plan/folders.js +82 -0
- package/dist/plan/names.js +93 -0
- package/dist/plan/ownership.js +316 -0
- package/dist/plan/planner.js +669 -0
- package/dist/plan/rehome.js +101 -0
- package/dist/plan/report.js +407 -0
- package/dist/sources/cache.js +89 -0
- package/dist/sources/claude.js +297 -0
- package/dist/sources/codex.js +496 -0
- package/dist/sources/flatten.js +23 -0
- package/dist/sources/jsonl.js +169 -0
- package/dist/sources/native.js +233 -0
- package/dist/sources/opencode.js +483 -0
- package/dist/sources/pi.js +133 -0
- package/dist/sources/registry.js +67 -0
- package/dist/sources/types.js +80 -0
- package/dist/t3/api.js +492 -0
- package/dist/t3/auth.js +248 -0
- package/dist/t3/compat.js +62 -0
- package/dist/t3/decode.js +408 -0
- package/dist/t3/errors.js +185 -0
- package/dist/t3/rpc.js +185 -0
- package/dist/t3/runtime.js +80 -0
- package/dist/ui/caps.js +56 -0
- package/dist/ui/components.js +202 -0
- package/dist/ui/layout.js +205 -0
- package/dist/ui/list.js +423 -0
- package/dist/ui/locale.js +73 -0
- package/dist/ui/organizePreview.js +72 -0
- package/dist/ui/progress.js +237 -0
- package/dist/ui/style.js +32 -0
- package/dist/ui/terminal.js +126 -0
- package/dist/ui/text.js +186 -0
- package/package.json +58 -4
- package/skills/t3code-sessions/SKILL.md +183 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
|
|
2
|
+
import { uuidV5 } from "../core/uuid.js";
|
|
3
|
+
import { claudeAdapter } from "./claude.js";
|
|
4
|
+
import { codexAdapter } from "./codex.js";
|
|
5
|
+
import { opencodeAdapter } from "./opencode.js";
|
|
6
|
+
import { piAdapter } from "./pi.js";
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
/** Every source adapter, in report order: the native ones, then the converted ones. */
|
|
10
|
+
export function allAdapters() {
|
|
11
|
+
return [claudeAdapter, codexAdapter, piAdapter, opencodeAdapter];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The harness's sessions are converted into Claude transcripts by t3sm (its adapter's `mode` is "convert"); T3 Code
|
|
16
|
+
* never reads them itself. The single source of truth for planner and apply.
|
|
17
|
+
*/
|
|
18
|
+
export function isConvertHarness(id ) {
|
|
19
|
+
return allAdapters().some((a) => a.id === id && a.mode === "convert");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether this session goes through conversion: its own `mode` when it carries one (Codex compressed rollouts are
|
|
24
|
+
* converted while plain ones are native), else its adapter's. Planner, apply and the importer decide per session.
|
|
25
|
+
*/
|
|
26
|
+
export function isConvertSession(s , isConvert = isConvertHarness) {
|
|
27
|
+
return s.mode !== undefined ? s.mode === "convert" : isConvert(s.harness);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Every id one session of `harness` can have in T3 Code: its native id (T3 imports the file itself, or the session was
|
|
32
|
+
* started inside T3) and/or the uuid of its converted Claude transcript (`uuidV5("<harness>:<nativeId>")`). A
|
|
33
|
+
* convert-mode harness has only the uuid; a native one without a reader only the native id; a native harness that also
|
|
34
|
+
* converts some sessions (Codex: compressed rollouts) has both, and they are ONE session: a thread under either form
|
|
35
|
+
* means it is already in T3. Order: native id first.
|
|
36
|
+
*/
|
|
37
|
+
export function sessionForms(harness , nativeId ) {
|
|
38
|
+
const a = allAdapters().find((x) => x.id === harness);
|
|
39
|
+
const converted = uuidV5(`${harness}:${nativeId}`);
|
|
40
|
+
if (!a) return [nativeId];
|
|
41
|
+
if (a.mode === "convert") return [converted];
|
|
42
|
+
return typeof a.read === "function" ? [nativeId, converted] : [nativeId];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The session ids T3 holds a thread for, under any instance: `import:<instance>:<id>` thread ids and native refs. */
|
|
46
|
+
export function sessionIdsInT3(threads ) {
|
|
47
|
+
const out = new Set ();
|
|
48
|
+
for (const t of threads) {
|
|
49
|
+
const m = /^import:[^:]+:(.+)$/.exec(t.id);
|
|
50
|
+
if (m) out.add(m[1] );
|
|
51
|
+
if (t.nativeSessionId) out.add(t.nativeSessionId);
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The forms of `s` other than the one this item imports (`own`): a thread under one of them means it is in T3. */
|
|
57
|
+
export function otherForms(s , own ) {
|
|
58
|
+
return sessionForms(s.harness, s.nativeId).filter((f) => f !== own);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The harness has sessions t3sm converts (its adapter can `read` them): OpenCode, and Codex for compressed rollouts.
|
|
63
|
+
* Provenance checks use this: a converted transcript or journaled conversion of such a harness is t3sm's own.
|
|
64
|
+
*/
|
|
65
|
+
export function hasConverter(id ) {
|
|
66
|
+
return allAdapters().some((a) => a.id === id && typeof a.read === "function");
|
|
67
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Whether a harness can be read on this machine: `absent` (not installed / no sessions), `ok`, `drift` (its storage
|
|
18
|
+
* no longer has what the adapter reads; doctor warns) or `unreadable` (present but could not be read; doctor warns).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
/** A harness's storage no longer has what the adapter reads (a newer or older version of the agent). */
|
|
57
|
+
export class HarnessSchemaError extends Error {
|
|
58
|
+
name = "HarnessSchemaError";
|
|
59
|
+
harness ;
|
|
60
|
+
constructor(harness , message ) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.harness = harness;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The source kept changing while it was being read: try again next run (deferred, not failed). */
|
|
67
|
+
export class SourceBusyError extends Error {
|
|
68
|
+
name = "SourceBusyError";
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** As of the state read (the run's pinned snapshot), the session was updated within ACTIVE_WINDOW_MS: in use; next run. */
|
|
72
|
+
export class SessionActiveError extends Error {
|
|
73
|
+
name = "SessionActiveError";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A transcript modified more recently than this is considered in use and is never touched. */
|
|
77
|
+
export { ACTIVE_WINDOW_MS } from "../core/activity.js";
|
|
78
|
+
/** T3 Code reads `cwd` only from the first 1 MiB / 1000 records of a transcript (spike S2). */
|
|
79
|
+
export const CWD_SCAN_MAX_BYTES = 1_048_576;
|
|
80
|
+
export const CWD_SCAN_MAX_RECORDS = 1000;
|
package/dist/t3/api.js
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
// Typed façade over T3 Code: every command reads and changes T3 only through here, and every response is decoded
|
|
2
|
+
// strictly (decode.ts) so a changed nightly shape stops t3sm (exit 4) instead of being acted on blindly.
|
|
3
|
+
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { T3AuthError, T3HttpError, T3Incompatible, T3NotRunning, ShapeError, pinSecret } from "./errors.js";
|
|
7
|
+
import { isT3Running, parseLocalOrigin, readServerRuntime, resolveT3Cli } from "./runtime.js";
|
|
8
|
+
import { DEFAULT_SCOPES, issueSessionToken, mintWsTicket, revokeSession, } from "./auth.js";
|
|
9
|
+
import { RpcClient, buildWsUrl, webSocketTransport, } from "./rpc.js";
|
|
10
|
+
import { SETTLE_BACKDATE, compatGate } from "./compat.js";
|
|
11
|
+
import {
|
|
12
|
+
decodeArchivedShell, decodeConfig, decodeDispatch, decodeEnvironment, decodeImport, decodeProject, decodeProjects, decodeScan,
|
|
13
|
+
decodeServerSettings, decodeShell,
|
|
14
|
+
|
|
15
|
+
} from "./decode.js";
|
|
16
|
+
import { normalizeCwd, sameCwd } from "../core/paths.js";
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
const HTTP_TIMEOUT_MS = 15_000;
|
|
22
|
+
const AGENT_SESSIONS_TIMEOUT_MS = 120_000;
|
|
23
|
+
const INSTANCE_ID_RE = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
|
|
24
|
+
const ACCENT_RE = /^#[0-9a-fA-F]{6}$/;
|
|
25
|
+
const ENV_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
26
|
+
const GROUP_KEY_HOME_RE = /^[^:]+:home:(.+)$/s;
|
|
27
|
+
|
|
28
|
+
/** The part of RpcClient the API uses (a fake replays fixtures in tests). */
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
const isObj = (u ) => typeof u === "object" && u !== null && !Array.isArray(u);
|
|
98
|
+
const str = (u ) => (typeof u === "string" ? u : null);
|
|
99
|
+
|
|
100
|
+
function checkThreadId(id ) {
|
|
101
|
+
if (typeof id !== "string" || id === "") throw new Error("threadId must be a non-empty string");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function checkInstanceId(id ) {
|
|
105
|
+
if (typeof id !== "string" || id.length === 0 || id.length > 64 || !INSTANCE_ID_RE.test(id)) {
|
|
106
|
+
throw new Error(`invalid T3 instance id ${JSON.stringify(id)}: must match ${INSTANCE_ID_RE} and be at most 64 chars`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Absolute native path for T3 (S4: never build homePath from string literals; a typo path is silently accepted). */
|
|
111
|
+
function nativeHome(p , platform ) {
|
|
112
|
+
if (typeof p !== "string" || p.trim() === "") throw new Error("homePath must be a non-empty absolute path");
|
|
113
|
+
if (platform === "win32") {
|
|
114
|
+
if (!/^[A-Za-z]:[\\/]/.test(p) && !/^[\\/]{2}[^\\/]/.test(p)) throw new Error(`homePath must be absolute: ${p}`);
|
|
115
|
+
return path.win32.normalize(p);
|
|
116
|
+
}
|
|
117
|
+
if (!path.posix.isAbsolute(p)) throw new Error(`homePath must be absolute: ${p}`);
|
|
118
|
+
return path.posix.normalize(p);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function homeFromGroupKey(groupKey ) {
|
|
122
|
+
const m = groupKey ? GROUP_KEY_HOME_RE.exec(groupKey) : null;
|
|
123
|
+
return m ? m[1] : null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function configuredHome(entry ) {
|
|
127
|
+
const c = entry?.config;
|
|
128
|
+
return isObj(c) && typeof c.homePath === "string" && c.homePath !== "" ? c.homePath : null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Every instance T3 knows: live `providers[]` first (implicit and unavailable ones included), then explicit settings
|
|
133
|
+
* entries not (yet) in providers[]. homePath = configured `config.homePath`, else `runtimePaths.homePath`, else the
|
|
134
|
+
* `<kind>:home:<dir>` parse of `continuation.groupKey` (server.ts 240-245), else null.
|
|
135
|
+
*/
|
|
136
|
+
function listInstances(cfg ) {
|
|
137
|
+
const map = cfg.settings.providerInstances;
|
|
138
|
+
const out = [];
|
|
139
|
+
const seen = new Set ();
|
|
140
|
+
for (const p of cfg.providers) {
|
|
141
|
+
seen.add(p.instanceId);
|
|
142
|
+
const entry = Object.hasOwn(map, p.instanceId) ? map[p.instanceId] : undefined;
|
|
143
|
+
out.push({
|
|
144
|
+
instanceId: p.instanceId, driver: p.driver,
|
|
145
|
+
homePath: configuredHome(entry) ?? p.runtimeHomePath ?? homeFromGroupKey(p.continuation?.groupKey),
|
|
146
|
+
displayName: p.displayName ?? entry?.displayName ?? p.driver, accentColor: p.accentColor ?? entry?.accentColor ?? null,
|
|
147
|
+
email: p.auth.email, authStatus: p.auth.status, enabled: p.enabled, availability: p.availability,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
for (const [id, entry] of Object.entries(map)) {
|
|
151
|
+
if (seen.has(id)) continue;
|
|
152
|
+
out.push({
|
|
153
|
+
instanceId: id, driver: entry.driver, homePath: configuredHome(entry), displayName: entry.displayName ?? entry.driver,
|
|
154
|
+
accentColor: entry.accentColor ?? null, email: null, authStatus: null, enabled: entry.enabled ?? true, availability: "unavailable",
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Claude-driver instances as planner specs (homePath normalized with normalizeCwd; env entries with string values only). */
|
|
161
|
+
export function instancesFromConfig(cfg , platform = process.platform) {
|
|
162
|
+
const map = cfg.settings.providerInstances;
|
|
163
|
+
const out = [];
|
|
164
|
+
for (const i of listInstances(cfg)) {
|
|
165
|
+
if (i.driver !== "claudeAgent" || i.homePath === null) continue;
|
|
166
|
+
const entry = Object.hasOwn(map, i.instanceId) ? map[i.instanceId] : undefined;
|
|
167
|
+
const environment = (entry?.environment ?? [])
|
|
168
|
+
.filter((e) => typeof e.value === "string")
|
|
169
|
+
.map((e) => ({ name: e.name, value: e.value, sensitive: e.sensitive }));
|
|
170
|
+
out.push({ id: i.instanceId, driver: "claudeAgent", displayName: i.displayName, accentColor: i.accentColor, homePath: normalizeCwd(i.homePath, platform), environment });
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function createT3Api(deps ) {
|
|
176
|
+
const { origin, token, rpc, version } = deps;
|
|
177
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
178
|
+
const notice = deps.onNotice ?? ((line ) => { try { process.stderr.write(`${line.replace(/[\r\n]+/g, " ")}\n`); } catch { /* ignore */ } });
|
|
179
|
+
const newId = deps.newId ?? randomUUID;
|
|
180
|
+
const platform = deps.platform ?? process.platform;
|
|
181
|
+
pinSecret(token);
|
|
182
|
+
|
|
183
|
+
async function http (method , pathname , decode , opts = {}) {
|
|
184
|
+
const endpoint = `${method} ${pathname}`;
|
|
185
|
+
const base = parseLocalOrigin(origin);
|
|
186
|
+
if (!base) throw new T3AuthError("refusing to send credentials to a non-local origin");
|
|
187
|
+
const headers = { authorization: `Bearer ${token}`, ...(opts.headers ?? {}) };
|
|
188
|
+
let body ;
|
|
189
|
+
if (opts.body !== undefined) { headers["content-type"] = "application/json"; body = JSON.stringify(opts.body); }
|
|
190
|
+
let res ;
|
|
191
|
+
let text ;
|
|
192
|
+
try {
|
|
193
|
+
res = await fetchImpl(new URL(pathname, base).href, { method, headers, body, redirect: "error", signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) });
|
|
194
|
+
text = await res.text();
|
|
195
|
+
} catch (e) {
|
|
196
|
+
const timeout = e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
|
|
197
|
+
throw new T3HttpError(endpoint, null, { message: timeout ? `timed out after ${HTTP_TIMEOUT_MS / 1000} s` : "could not reach T3 Code (refused, reset or redirected)" });
|
|
198
|
+
}
|
|
199
|
+
if (!res.ok) {
|
|
200
|
+
let b = null;
|
|
201
|
+
try { b = JSON.parse(text); } catch { /* empty or non-JSON error body */ }
|
|
202
|
+
const o = isObj(b) ? b : {};
|
|
203
|
+
throw new T3HttpError(endpoint, res.status, { errorTag: str(o._tag), code: str(o.code), reason: str(o.reason) });
|
|
204
|
+
}
|
|
205
|
+
let parsed ;
|
|
206
|
+
try { parsed = JSON.parse(text); } catch { throw new ShapeError(endpoint, "$", "JSON body"); }
|
|
207
|
+
return decode(parsed);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const getConfig = () => rpc.call("server.getConfig", {}, decodeConfig);
|
|
211
|
+
const listProjects = async () => (await http("GET", "/api/projects", decodeProjects)).filter((p) => !p.deleted);
|
|
212
|
+
|
|
213
|
+
async function defaultModelFor(instanceId ) {
|
|
214
|
+
const cfg = await getConfig();
|
|
215
|
+
const prov = cfg.providers.find((p) => p.instanceId === instanceId);
|
|
216
|
+
const own = prov?.models.find((m) => m.isDefault);
|
|
217
|
+
if (own) return own.slug;
|
|
218
|
+
const map = cfg.settings.providerInstances;
|
|
219
|
+
const driver = prov?.driver ?? (Object.hasOwn(map, instanceId) ? map[instanceId] .driver : undefined);
|
|
220
|
+
if (!driver) throw new Error(`T3 instance ${instanceId} not found`);
|
|
221
|
+
// Not probed yet (just created): the default model T3 reports for the same driver.
|
|
222
|
+
for (const p of cfg.providers) {
|
|
223
|
+
if (p.driver !== driver) continue;
|
|
224
|
+
const m = p.models.find((x) => x.isDefault);
|
|
225
|
+
if (m) return m.slug;
|
|
226
|
+
}
|
|
227
|
+
throw new Error(`no default model known for T3 instance ${instanceId} (driver ${driver}); pass a model explicitly`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function updateInstance(instanceId , mutation ) {
|
|
231
|
+
// Per-entry mutation only. NEVER patch.providerInstances: it replaces the whole map (S4 §2).
|
|
232
|
+
const settings = await rpc.call("server.updateSettings", { patch: {}, providerInstanceMutation: mutation }, decodeServerSettings);
|
|
233
|
+
if (!Object.hasOwn(settings.providerInstances, instanceId)) {
|
|
234
|
+
throw new ShapeError("server.updateSettings", `$.providerInstances[${JSON.stringify(instanceId)}]`, "the mutated instance");
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const dispatch = async (type , threadId , extra = {}) => {
|
|
239
|
+
checkThreadId(threadId);
|
|
240
|
+
await rpc.call("orchestration.dispatchCommand", { type, commandId: newId(), threadId, ...extra }, decodeDispatch);
|
|
241
|
+
};
|
|
242
|
+
const backdate = deps.backdate ?? SETTLE_BACKDATE;
|
|
243
|
+
|
|
244
|
+
const mutateProject = async (type , projectId , extra = {}) => {
|
|
245
|
+
if (typeof projectId !== "string" || projectId === "") throw new Error("projectId must be a non-empty string");
|
|
246
|
+
await http("POST", "/api/projects/mutate", (u) => decodeProject(u), { body: { type, commandId: newId(), projectId, ...extra } });
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
async function autoSettleDays() {
|
|
250
|
+
const settings = (await getConfig()).settings;
|
|
251
|
+
// A value outside 1..90 (a newer T3 Code): organize neither offers nor makes a change to it.
|
|
252
|
+
if (settings.sidebarAutoSettleUnknown === true) throw new Error("T3 Code reports an auto-settle value t3sm does not know; t3sm leaves that setting alone");
|
|
253
|
+
const days = settings.sidebarAutoSettleAfterDays;
|
|
254
|
+
if (days === undefined) throw new ShapeError("server.getConfig", "$.settings.sidebarAutoSettleAfterDays", "integer 1..90 or null");
|
|
255
|
+
return days;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
let closing = null;
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
version,
|
|
262
|
+
listProjects,
|
|
263
|
+
async listThreads() {
|
|
264
|
+
const active = await http("GET", "/api/orchestration/shell", decodeShell, { headers: { "x-t3-orchestration-protocol": "2" } });
|
|
265
|
+
const archived = await rpc.call("orchestration.getArchivedShellSnapshot", {}, decodeArchivedShell);
|
|
266
|
+
const byId = new Map ();
|
|
267
|
+
for (const t of active) byId.set(t.id, t);
|
|
268
|
+
for (const t of archived) byId.set(t.id, t); // archived snapshot wins
|
|
269
|
+
return [...byId.values()];
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
createProject: (root, title) =>
|
|
273
|
+
http("POST", "/api/projects/mutate", (u) => decodeProject(u), {
|
|
274
|
+
body: { type: "project.create", commandId: newId(), projectId: newId(), title, workspaceRoot: root, createWorkspaceRootIfMissing: false },
|
|
275
|
+
}),
|
|
276
|
+
|
|
277
|
+
async setProjectDefault(projectId, instanceId, model) {
|
|
278
|
+
const current = (await listProjects()).find((p) => p.id === projectId);
|
|
279
|
+
if (!current) throw new Error(`T3 project ${projectId} not found`);
|
|
280
|
+
let selection = null;
|
|
281
|
+
if (instanceId !== null) {
|
|
282
|
+
checkInstanceId(instanceId);
|
|
283
|
+
selection = { instanceId, model: model ?? (await defaultModelFor(instanceId)) };
|
|
284
|
+
}
|
|
285
|
+
await http("POST", "/api/projects/mutate", (u) => decodeProject(u), {
|
|
286
|
+
body: { type: "project.update", commandId: newId(), projectId, defaultModelSelection: selection },
|
|
287
|
+
});
|
|
288
|
+
return { previous: current.defaultModelSelection };
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
getConfig,
|
|
292
|
+
providerInstances: async () => listInstances(await getConfig()),
|
|
293
|
+
|
|
294
|
+
async addInstance(spec) {
|
|
295
|
+
checkInstanceId(spec.id);
|
|
296
|
+
if (spec.driver !== "claudeAgent") throw new Error(`unsupported driver ${String(spec.driver)}`);
|
|
297
|
+
if (typeof spec.displayName !== "string" || spec.displayName.trim() === "") throw new Error("displayName must be non-empty");
|
|
298
|
+
if (spec.accentColor !== null && !ACCENT_RE.test(spec.accentColor)) throw new Error(`accentColor must be #RRGGBB, got ${JSON.stringify(spec.accentColor)}`);
|
|
299
|
+
for (const e of spec.environment) {
|
|
300
|
+
if (!ENV_NAME_RE.test(e.name) || e.name.length > 128 || typeof e.value !== "string" || typeof e.sensitive !== "boolean") throw new Error(`invalid environment entry ${JSON.stringify(e.name)}`);
|
|
301
|
+
}
|
|
302
|
+
const instance = { driver: spec.driver, displayName: spec.displayName.trim() };
|
|
303
|
+
if (spec.accentColor !== null) instance.accentColor = spec.accentColor;
|
|
304
|
+
instance.enabled = true;
|
|
305
|
+
instance.config = { homePath: nativeHome(spec.homePath, platform) };
|
|
306
|
+
if (spec.environment.length) instance.environment = spec.environment.map((e) => ({ name: e.name, value: e.value, sensitive: e.sensitive }));
|
|
307
|
+
await updateInstance(spec.id, { operation: "create", instanceId: spec.id, instance });
|
|
308
|
+
},
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Upsert replaces the entry whole (S4 §2), so the FULL entry is sent:
|
|
312
|
+
* - explicit entry in settings.providerInstances: that entry unchanged except `config.homePath` (other config keys kept);
|
|
313
|
+
* - implicit instance (settings map has no such id; it exists only in providers[]): `{driver, config:{homePath}}`,
|
|
314
|
+
* exactly the S4 §6 pin. No displayName/accentColor/enabled are invented, so nothing is renamed or re-enabled.
|
|
315
|
+
* previous = the explicit entry before the change, or null when the instance was implicit.
|
|
316
|
+
* An explicit entry whose config.homePath already equals the requested home is left alone: {previous, changed:false}.
|
|
317
|
+
*/
|
|
318
|
+
async pinInstanceHome(instanceId, homePath) {
|
|
319
|
+
checkInstanceId(instanceId);
|
|
320
|
+
const home = nativeHome(homePath, platform);
|
|
321
|
+
const cfg = await getConfig();
|
|
322
|
+
const map = cfg.settings.providerInstances;
|
|
323
|
+
const existing = Object.hasOwn(map, instanceId) ? map[instanceId] : null;
|
|
324
|
+
let instance ;
|
|
325
|
+
if (existing && isObj(existing.config) && typeof existing.config.homePath === "string" && sameCwd(existing.config.homePath, home, platform)) {
|
|
326
|
+
return { previous: structuredClone(existing), changed: false };
|
|
327
|
+
}
|
|
328
|
+
if (existing) {
|
|
329
|
+
const c = existing.config;
|
|
330
|
+
if (c !== undefined && c !== null && !isObj(c)) throw new Error(`T3 instance ${instanceId} has a non-object config; refusing to overwrite it`);
|
|
331
|
+
instance = { ...structuredClone(existing), config: { ...(isObj(c) ? structuredClone(c) : {}), homePath: home } };
|
|
332
|
+
} else {
|
|
333
|
+
const p = cfg.providers.find((x) => x.instanceId === instanceId);
|
|
334
|
+
if (!p) throw new Error(`T3 instance ${instanceId} not found`);
|
|
335
|
+
instance = { driver: p.driver, config: { homePath: home } };
|
|
336
|
+
}
|
|
337
|
+
await updateInstance(instanceId, { operation: "upsert", instanceId, instance });
|
|
338
|
+
return { previous: existing ? structuredClone(existing) : null, changed: true };
|
|
339
|
+
},
|
|
340
|
+
|
|
341
|
+
async updateInstanceAppearance(instanceId, ap) {
|
|
342
|
+
checkInstanceId(instanceId);
|
|
343
|
+
if (ap.displayName !== undefined && (typeof ap.displayName !== "string" || ap.displayName.trim() === "")) throw new Error("displayName must be non-empty");
|
|
344
|
+
if (ap.accentColor !== undefined && !ACCENT_RE.test(ap.accentColor)) throw new Error(`accentColor must be #RRGGBB, got ${JSON.stringify(ap.accentColor)}`);
|
|
345
|
+
const cfg = await getConfig();
|
|
346
|
+
const map = cfg.settings.providerInstances;
|
|
347
|
+
const existing = Object.hasOwn(map, instanceId) ? map[instanceId] : null;
|
|
348
|
+
let instance ;
|
|
349
|
+
if (existing) instance = structuredClone(existing) ;
|
|
350
|
+
else {
|
|
351
|
+
const p = cfg.providers.find((x) => x.instanceId === instanceId);
|
|
352
|
+
if (!p) throw new Error(`T3 instance ${instanceId} not found`);
|
|
353
|
+
// Implicit instance: pin its home in the same upsert so the explicit entry cannot drift (S4 §6).
|
|
354
|
+
const home = listInstances(cfg).find((x) => x.instanceId === instanceId)?.homePath ?? null;
|
|
355
|
+
instance = home !== null ? { driver: p.driver, config: { homePath: nativeHome(home, platform) } } : { driver: p.driver };
|
|
356
|
+
}
|
|
357
|
+
const next = { ...instance };
|
|
358
|
+
if (ap.displayName !== undefined) next.displayName = ap.displayName.trim();
|
|
359
|
+
if (ap.accentColor !== undefined) next.accentColor = ap.accentColor;
|
|
360
|
+
if (existing && JSON.stringify(next) === JSON.stringify(instance)) return { previous: structuredClone(existing), changed: false };
|
|
361
|
+
await updateInstance(instanceId, { operation: "upsert", instanceId, instance: next });
|
|
362
|
+
return { previous: existing ? structuredClone(existing) : null, changed: true };
|
|
363
|
+
},
|
|
364
|
+
|
|
365
|
+
archiveThread: (threadId) => dispatch("thread.archive", threadId),
|
|
366
|
+
unarchiveThread: (threadId) => dispatch("thread.unarchive", threadId),
|
|
367
|
+
|
|
368
|
+
settleThread: (threadId, settledAt) => dispatch("thread.settle", threadId, backdate && settledAt !== undefined ? { settledAt } : {}),
|
|
369
|
+
async unsettleThread(threadId) {
|
|
370
|
+
checkThreadId(threadId);
|
|
371
|
+
await rpc.call("orchestration.dispatchCommand", { type: "thread.unsettle", commandId: newId(), threadId, reason: "user" }, decodeDispatch);
|
|
372
|
+
},
|
|
373
|
+
async setThreadTitle(threadId, title) {
|
|
374
|
+
checkThreadId(threadId);
|
|
375
|
+
if (typeof title !== "string" || title.trim() === "") throw new Error("title must be a non-empty string");
|
|
376
|
+
await rpc.call("orchestration.dispatchCommand", { type: "thread.metadata.update", commandId: newId(), threadId, title }, decodeDispatch);
|
|
377
|
+
},
|
|
378
|
+
|
|
379
|
+
setProjectPinned(projectId, pinned) {
|
|
380
|
+
if (typeof pinned !== "boolean") throw new Error("pinned must be a boolean");
|
|
381
|
+
return mutateProject("project.update", projectId, { pinned });
|
|
382
|
+
},
|
|
383
|
+
async setProjectTitle(projectId, title) {
|
|
384
|
+
if (typeof title !== "string" || title.trim() === "") throw new Error("title must be a non-empty string");
|
|
385
|
+
await mutateProject("project.update", projectId, { title });
|
|
386
|
+
},
|
|
387
|
+
deleteProject: (projectId) => mutateProject("project.delete", projectId),
|
|
388
|
+
|
|
389
|
+
getServerSetting: (key) => {
|
|
390
|
+
if (key !== "sidebarAutoSettleAfterDays") throw new Error(`unsupported server setting ${JSON.stringify(key)}`);
|
|
391
|
+
return autoSettleDays();
|
|
392
|
+
},
|
|
393
|
+
async setAutoSettleAfterDays(days) {
|
|
394
|
+
if (days !== null && (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > 90)) {
|
|
395
|
+
throw new Error(`auto-settle days must be an integer from 1 to 90, or null to turn it off; got ${String(days)}`);
|
|
396
|
+
}
|
|
397
|
+
const previous = await autoSettleDays();
|
|
398
|
+
if (previous === days) return { previous };
|
|
399
|
+
const settings = await rpc.call("server.updateSettings", { patch: { sidebarAutoSettleAfterDays: days } }, decodeServerSettings);
|
|
400
|
+
if (settings.sidebarAutoSettleAfterDays !== days) throw new ShapeError("server.updateSettings", "$.sidebarAutoSettleAfterDays", `the requested value ${days === null ? "null" : days}`);
|
|
401
|
+
return { previous };
|
|
402
|
+
},
|
|
403
|
+
|
|
404
|
+
scanSessions: () => rpc.call("agentSessions.scan", {}, decodeScan, AGENT_SESSIONS_TIMEOUT_MS),
|
|
405
|
+
importSessions: (projectId, root) =>
|
|
406
|
+
rpc.call("agentSessions.import", { projectId, expectedWorkspaceRoot: root }, decodeImport, AGENT_SESSIONS_TIMEOUT_MS),
|
|
407
|
+
|
|
408
|
+
close() {
|
|
409
|
+
closing ??= (async () => {
|
|
410
|
+
try { rpc.close(); } catch { /* already closed */ }
|
|
411
|
+
if (!deps.onClose) return;
|
|
412
|
+
try { await deps.onClose(); } catch {
|
|
413
|
+
notice("t3sm: could not revoke the T3 Code bearer session; it expires on its own within 1 h.");
|
|
414
|
+
}
|
|
415
|
+
})();
|
|
416
|
+
return closing;
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Connects to the running T3 Code: liveness (T3NotRunning, exit 3) -> environment read + compatibility gate
|
|
442
|
+
* (T3Incompatible for a wrong orchestration protocol, ShapeError for a changed shape, exit 4; done before any token exists,
|
|
443
|
+
* so a refused server leaves no session behind; an untested version only warns)
|
|
444
|
+
* -> least-privilege token -> ws ticket -> socket. If anything after the token fails, the session is revoked
|
|
445
|
+
* (best effort) and the original error is rethrown.
|
|
446
|
+
*/
|
|
447
|
+
export async function connectT3(home , opts ) {
|
|
448
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
449
|
+
const rt = await readServerRuntime(home);
|
|
450
|
+
if (!rt || !(await isT3Running(home, fetchImpl))) throw new T3NotRunning();
|
|
451
|
+
|
|
452
|
+
const env = await readEnvironment(rt.origin, fetchImpl);
|
|
453
|
+
if (env.orchestrationProtocolVersion !== 2) {
|
|
454
|
+
throw new T3Incompatible(env.serverVersion, `T3 Code ${env.serverVersion} speaks orchestration protocol ${env.orchestrationProtocolVersion}; t3sm needs protocol 2.`);
|
|
455
|
+
}
|
|
456
|
+
compatGate(env.serverVersion, { allowUntested: opts.allowUntested, onNotice: opts.onNotice });
|
|
457
|
+
|
|
458
|
+
const cli = opts.cli ?? resolveT3Cli(home, process.platform, process.env.PATH ?? "");
|
|
459
|
+
if (!cli) throw new T3AuthError("T3 Code CLI (t3) not found in ~/.t3/bin or PATH");
|
|
460
|
+
const scopes = [...DEFAULT_SCOPES, ...(opts.manageProviders ? ["providers:manage"] : []), ...(opts.writeSettings ? ["settings:write"] : [])];
|
|
461
|
+
const { token, sessionId } = await issueSessionToken(cli, { scopes, run: opts.run });
|
|
462
|
+
const revoke = () => revokeSession(cli, sessionId, opts.run, token);
|
|
463
|
+
|
|
464
|
+
let transport ;
|
|
465
|
+
try {
|
|
466
|
+
const ticket = await mintWsTicket(rt.origin, token, fetchImpl);
|
|
467
|
+
transport = await (opts.transportFactory ?? webSocketTransport)(buildWsUrl(rt.origin, ticket));
|
|
468
|
+
} catch (e) {
|
|
469
|
+
try { await revoke(); } catch { /* never mask the original error */ }
|
|
470
|
+
throw e;
|
|
471
|
+
}
|
|
472
|
+
return createT3Api({
|
|
473
|
+
origin: rt.origin, token, rpc: new RpcClient(transport), version: env.serverVersion, fetchImpl,
|
|
474
|
+
newId: opts.newId, onClose: revoke, onNotice: opts.onNotice,
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async function readEnvironment(origin , fetchImpl ) {
|
|
479
|
+
const endpoint = "GET /.well-known/t3/environment";
|
|
480
|
+
const base = parseLocalOrigin(origin);
|
|
481
|
+
if (!base) throw new T3NotRunning();
|
|
482
|
+
let text ;
|
|
483
|
+
let res ;
|
|
484
|
+
try {
|
|
485
|
+
res = await fetchImpl(new URL("/.well-known/t3/environment", base).href, { redirect: "error", signal: AbortSignal.timeout(HTTP_TIMEOUT_MS) });
|
|
486
|
+
text = await res.text();
|
|
487
|
+
} catch { throw new T3NotRunning(); }
|
|
488
|
+
if (!res.ok) throw new T3HttpError(endpoint, res.status);
|
|
489
|
+
let parsed ;
|
|
490
|
+
try { parsed = JSON.parse(text); } catch { throw new ShapeError(endpoint, "$", "JSON body"); }
|
|
491
|
+
return decodeEnvironment(parsed);
|
|
492
|
+
}
|