@cortexkit/common-auth 0.23.0 → 0.25.0
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/dist/claustrum/consumer.d.ts +7 -1
- package/dist/claustrum/consumer.js +17 -2
- package/dist/claustrum/enrollment.d.ts +5 -0
- package/dist/claustrum/enrollment.js +27 -0
- package/dist/claustrum/errors.d.ts +1 -1
- package/dist/claustrum/index.d.ts +1 -1
- package/dist/claustrum/index.js +1 -1
- package/dist/claustrum/roster.d.ts +31 -0
- package/dist/claustrum/roster.js +72 -0
- package/dist/commands/builtins.d.ts +37 -0
- package/dist/commands/builtins.js +95 -13
- package/dist/commands/index.d.ts +1 -1
- package/dist/fs/private-files.d.ts +2 -0
- package/dist/fs/private-files.js +49 -3
- package/dist/opencode2/install.d.ts +3 -2
- package/dist/opencode2/install.js +184 -63
- package/dist/opencode2/types.d.ts +43 -6
- package/dist/setup/enroll.d.ts +25 -4
- package/dist/setup/enroll.js +116 -34
- package/dist/setup/index.d.ts +1 -0
- package/dist/setup/index.js +1 -0
- package/dist/setup/process-fence.d.ts +7 -0
- package/dist/setup/process-fence.js +56 -1
- package/dist/setup/types.d.ts +5 -0
- package/package.json +2 -2
|
@@ -97,8 +97,9 @@ function applyHeaderEditsTo(target, edits) {
|
|
|
97
97
|
* whether output has started and when the response ended, attributed to
|
|
98
98
|
* an attempt by the rules below;
|
|
99
99
|
* - `retry` asks the host to retry at once when an account was refused
|
|
100
|
-
* before any output
|
|
101
|
-
*
|
|
100
|
+
* before any output and `chooseAccount` names another account for the
|
|
101
|
+
* next attempt, keeps the host's decision when the refused account was the
|
|
102
|
+
* last one that can serve, and refuses to retry once output has started.
|
|
102
103
|
*
|
|
103
104
|
* Attribution. A send belongs to the attempt named by the mark
|
|
104
105
|
* `model.request` left on it, so several attempts of one session and kind
|
|
@@ -159,6 +160,42 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
|
|
|
159
160
|
catch { }
|
|
160
161
|
};
|
|
161
162
|
const describe = (error) => error instanceof Error ? error.message : String(error);
|
|
163
|
+
// Adapter choices may enqueue work by session. Serialize their consumption
|
|
164
|
+
// and release so a new choice cannot overtake cleanup, even after forgetting.
|
|
165
|
+
const choiceWork = new Map();
|
|
166
|
+
const inChoiceOrder = (sessionID, run) => {
|
|
167
|
+
const result = (choiceWork.get(sessionID) ?? Promise.resolve()).then(run);
|
|
168
|
+
const settled = result.then(() => { }, () => { });
|
|
169
|
+
choiceWork.set(sessionID, settled);
|
|
170
|
+
void settled.then(() => {
|
|
171
|
+
if (choiceWork.get(sessionID) === settled)
|
|
172
|
+
choiceWork.delete(sessionID);
|
|
173
|
+
});
|
|
174
|
+
return result;
|
|
175
|
+
};
|
|
176
|
+
const afterChoiceWork = (sessionID, run) => {
|
|
177
|
+
const pending = choiceWork.get(sessionID);
|
|
178
|
+
return pending ? pending.then(() => afterChoiceWork(sessionID, run)) : run();
|
|
179
|
+
};
|
|
180
|
+
const releaseChoice = async (next) => {
|
|
181
|
+
try {
|
|
182
|
+
await adapter.dropChoice?.({ ...next.input, accountId: next.accountId });
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
warn('opencode2 auth dropChoice threw; the request is unaffected', {
|
|
186
|
+
sessionID: next.input.sessionID,
|
|
187
|
+
error: describe(error),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
const discardPending = (key) => {
|
|
192
|
+
const pending = pendingRetries.get(key);
|
|
193
|
+
pendingRetries.delete(key);
|
|
194
|
+
if (pending?.next) {
|
|
195
|
+
const next = pending.next;
|
|
196
|
+
void inChoiceOrder(pending.sessionID, () => releaseChoice(next));
|
|
197
|
+
}
|
|
198
|
+
};
|
|
162
199
|
const emit = async (event, payload) => {
|
|
163
200
|
const set = listeners.get(event);
|
|
164
201
|
if (!set || set.size === 0)
|
|
@@ -204,11 +241,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
|
|
|
204
241
|
/** The attempts of one session and kind, oldest first. */
|
|
205
242
|
const attemptsOf = (key) => [...attempts.values()].filter((rec) => rec.key === key);
|
|
206
243
|
const newestOf = (key) => attemptsOf(key).at(-1);
|
|
207
|
-
/** Forgets an attempt
|
|
244
|
+
/** Forgets an attempt and any pending retry it owns, or whose key is no longer held. */
|
|
208
245
|
const drop = (rec) => {
|
|
209
246
|
attempts.delete(rec.id);
|
|
210
|
-
if (
|
|
211
|
-
|
|
247
|
+
if (pendingRetries.get(rec.key)?.attemptId === rec.id ||
|
|
248
|
+
!attemptsOf(rec.key).length)
|
|
249
|
+
discardPending(rec.key);
|
|
212
250
|
};
|
|
213
251
|
const remember = (rec) => {
|
|
214
252
|
attempts.set(rec.id, rec);
|
|
@@ -300,18 +338,31 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
|
|
|
300
338
|
};
|
|
301
339
|
const select = async (scope, hook, assertActive, transport) => {
|
|
302
340
|
const key = keyOf(scope.sessionID, scope.kind);
|
|
303
|
-
const
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
341
|
+
const { input, accountId } = await afterChoiceWork(scope.sessionID, async () => {
|
|
342
|
+
assertActive();
|
|
343
|
+
const retried = pendingRetries.get(key);
|
|
344
|
+
pendingRetries.delete(key);
|
|
345
|
+
const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
|
|
346
|
+
supersede(key);
|
|
347
|
+
const next = retried?.next;
|
|
348
|
+
const matches = next !== undefined &&
|
|
349
|
+
next.input.modelID === scope.modelID &&
|
|
350
|
+
next.input.agent === scope.agent;
|
|
351
|
+
const input = {
|
|
352
|
+
...scope,
|
|
353
|
+
phase: 'request',
|
|
354
|
+
...(previousAccountId === undefined ? {} : { previousAccountId }),
|
|
355
|
+
...(retried?.rerouteFrom ? { rerouteFrom: retried.rerouteFrom } : {}),
|
|
356
|
+
};
|
|
357
|
+
if (next && !matches) {
|
|
358
|
+
await inChoiceOrder(scope.sessionID, () => releaseChoice(next));
|
|
359
|
+
assertActive();
|
|
360
|
+
}
|
|
361
|
+
const accountId = matches
|
|
362
|
+
? next.accountId
|
|
363
|
+
: await adapter.chooseAccount(input);
|
|
364
|
+
return { input, accountId };
|
|
365
|
+
});
|
|
315
366
|
assertActive();
|
|
316
367
|
let headers = {};
|
|
317
368
|
let data;
|
|
@@ -730,62 +781,130 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
|
|
|
730
781
|
}
|
|
731
782
|
const rec = picked;
|
|
732
783
|
await withSelection(rec.scope, async (assertActive) => {
|
|
784
|
+
const checkRetryActive = assertActive;
|
|
733
785
|
rec.judged = true;
|
|
734
|
-
let decision = hostDecision;
|
|
735
|
-
let reason;
|
|
736
|
-
let rerouteFrom;
|
|
737
786
|
const attempt = rec.attempt;
|
|
738
|
-
if (
|
|
739
|
-
decision = { retry: false };
|
|
740
|
-
reason = 'no-account';
|
|
741
|
-
}
|
|
742
|
-
else if (rec.outputStarted) {
|
|
743
|
-
// The user has already seen part of this answer; a retry would
|
|
744
|
-
// send it again.
|
|
745
|
-
decision = { retry: false };
|
|
746
|
-
reason = 'output-started';
|
|
747
|
-
}
|
|
748
|
-
else {
|
|
787
|
+
if (attempt && !rec.outputStarted) {
|
|
749
788
|
if (!rec.limit) {
|
|
750
789
|
const signal = adapter.limitFromError?.(draft.error, attempt);
|
|
751
790
|
if (signal)
|
|
752
791
|
noteLimit(rec, signal, 'error');
|
|
753
792
|
}
|
|
754
|
-
//
|
|
755
|
-
|
|
756
|
-
if (rec.ended) {
|
|
793
|
+
// Account selection must observe all feedback from the refused send.
|
|
794
|
+
if (rec.ended)
|
|
757
795
|
await rec.ended;
|
|
758
|
-
|
|
759
|
-
}
|
|
760
|
-
if (rec.limit) {
|
|
796
|
+
if (rec.limit)
|
|
761
797
|
await rec.limit.delivered;
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
798
|
+
}
|
|
799
|
+
checkRetryActive();
|
|
800
|
+
const { decision, reason } = await inChoiceOrder(rec.scope.sessionID, async () => {
|
|
801
|
+
checkRetryActive();
|
|
802
|
+
const old = pendingRetries.get(rec.key);
|
|
803
|
+
pendingRetries.delete(rec.key);
|
|
804
|
+
if (old?.next)
|
|
805
|
+
await releaseChoice(old.next);
|
|
806
|
+
checkRetryActive();
|
|
807
|
+
let decision = hostDecision;
|
|
808
|
+
let reason;
|
|
809
|
+
let rerouteFrom;
|
|
810
|
+
let next;
|
|
811
|
+
if (rec.accountId === undefined || !attempt) {
|
|
812
|
+
decision = { retry: false };
|
|
813
|
+
reason = 'no-account';
|
|
814
|
+
}
|
|
815
|
+
else if (rec.outputStarted) {
|
|
816
|
+
// The user has already seen part of this answer; a retry would
|
|
817
|
+
// send it again.
|
|
818
|
+
decision = { retry: false };
|
|
819
|
+
reason = 'output-started';
|
|
773
820
|
}
|
|
774
821
|
else {
|
|
775
|
-
|
|
822
|
+
if (rec.limit) {
|
|
823
|
+
const refused = {
|
|
824
|
+
accountId: rec.accountId,
|
|
825
|
+
limit: rec.limit.signal,
|
|
826
|
+
};
|
|
827
|
+
// Ask the adapter now, with the same input the next attempt
|
|
828
|
+
// would give it, which account serves that attempt. Rerouting
|
|
829
|
+
// is right only when that is another account: otherwise the
|
|
830
|
+
// next attempt would find no account (a `no-account` refusal
|
|
831
|
+
// the host treats as a defect and does not retry) or go back
|
|
832
|
+
// at once to the account that just refused.
|
|
833
|
+
let accountId;
|
|
834
|
+
const input = {
|
|
835
|
+
...rec.scope,
|
|
836
|
+
phase: 'retry',
|
|
837
|
+
previousAccountId: rec.accountId,
|
|
838
|
+
rerouteFrom: refused,
|
|
839
|
+
};
|
|
840
|
+
try {
|
|
841
|
+
accountId = await adapter.chooseAccount(input);
|
|
842
|
+
}
|
|
843
|
+
catch (error) {
|
|
844
|
+
// Treated as no other account: the host's own decision
|
|
845
|
+
// stands, and the next attempt asks the adapter again.
|
|
846
|
+
warn('opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry', {
|
|
847
|
+
sessionID: rec.scope.sessionID,
|
|
848
|
+
error: describe(error),
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
if (accountId !== undefined)
|
|
852
|
+
next = { accountId, input };
|
|
853
|
+
try {
|
|
854
|
+
checkRetryActive();
|
|
855
|
+
}
|
|
856
|
+
catch (error) {
|
|
857
|
+
// A selection revoked while the adapter was choosing cannot be used.
|
|
858
|
+
if (next)
|
|
859
|
+
await releaseChoice(next);
|
|
860
|
+
throw error;
|
|
861
|
+
}
|
|
862
|
+
if (accountId !== undefined && accountId !== rec.accountId) {
|
|
863
|
+
rec.rerouted = true;
|
|
864
|
+
rerouteFrom = refused;
|
|
865
|
+
// The next attempt takes this choice rather than asking
|
|
866
|
+
// again, so an account limited between here and the host's
|
|
867
|
+
// retry costs one refused send, which this hook judges
|
|
868
|
+
// again, rather than a `no-account` refusal.
|
|
869
|
+
// No delay: the next attempt goes to another account, and the
|
|
870
|
+
// host would otherwise wait out the refused account's backoff,
|
|
871
|
+
// or not retry at all for errors it deems final.
|
|
872
|
+
decision = { retry: true, delay: 0 };
|
|
873
|
+
reason = 'reroute';
|
|
874
|
+
}
|
|
875
|
+
else {
|
|
876
|
+
// The refused account keeps the host's wait and serves the
|
|
877
|
+
// retry. Undefined or a throw commits nothing: choose later.
|
|
878
|
+
reason = 'host-decides-last-account';
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
else {
|
|
882
|
+
reason = 'host-decides';
|
|
883
|
+
}
|
|
776
884
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
885
|
+
draft.decision = decision;
|
|
886
|
+
// The host's retry runs `model.request` again for this attempt's
|
|
887
|
+
// session and kind; that next attempt, and no other attempt of the
|
|
888
|
+
// session, is told what this one ended with.
|
|
889
|
+
if (decision.retry &&
|
|
890
|
+
rec.accountId !== undefined &&
|
|
891
|
+
attempts.has(rec.id)) {
|
|
892
|
+
pendingRetries.set(rec.key, {
|
|
893
|
+
attemptId: rec.id,
|
|
894
|
+
sessionID: rec.scope.sessionID,
|
|
895
|
+
accountId: rec.accountId,
|
|
896
|
+
...(rerouteFrom === undefined ? {} : { rerouteFrom }),
|
|
897
|
+
...(next === undefined ? {} : { next }),
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
else if (next) {
|
|
901
|
+
// Only the computed decision is final here: an incoming veto may
|
|
902
|
+
// have been overridden by a reroute to another account.
|
|
903
|
+
await releaseChoice(next);
|
|
904
|
+
}
|
|
905
|
+
return { decision, reason };
|
|
906
|
+
});
|
|
907
|
+
checkRetryActive();
|
|
789
908
|
await emit('retry', {
|
|
790
909
|
sessionID: draft.sessionID,
|
|
791
910
|
...(rec.accountId === undefined
|
|
@@ -815,7 +934,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
|
|
|
815
934
|
}
|
|
816
935
|
for (const [key, pending] of pendingRetries) {
|
|
817
936
|
if (pending.sessionID === sessionID)
|
|
818
|
-
|
|
937
|
+
discardPending(key);
|
|
819
938
|
}
|
|
820
939
|
};
|
|
821
940
|
const abort = new AbortController();
|
|
@@ -867,10 +986,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
|
|
|
867
986
|
for (const rec of attempts.values())
|
|
868
987
|
abandon(rec, 'the installation was disposed');
|
|
869
988
|
attempts.clear();
|
|
870
|
-
pendingRetries.
|
|
989
|
+
for (const key of pendingRetries.keys())
|
|
990
|
+
discardPending(key);
|
|
871
991
|
ownedSockets.clear();
|
|
872
992
|
latestTransportOwned.clear();
|
|
873
993
|
listeners.clear();
|
|
994
|
+
await Promise.all(choiceWork.values());
|
|
874
995
|
await Promise.all(registrations.map(async (registration) => {
|
|
875
996
|
try {
|
|
876
997
|
await registration.dispose();
|
|
@@ -53,6 +53,8 @@ export interface EventVerdict<Q> {
|
|
|
53
53
|
*/
|
|
54
54
|
export type HeaderEdits = Readonly<Record<string, string | null>>;
|
|
55
55
|
export interface ChooseAccountInput extends RequestScope {
|
|
56
|
+
/** Informational: the retry hook's advance choice, or a request's own choice. */
|
|
57
|
+
readonly phase: 'retry' | 'request';
|
|
56
58
|
/**
|
|
57
59
|
* The account of the attempt this one retries, when the retry hook just
|
|
58
60
|
* asked the host to retry an attempt of this session and kind; otherwise
|
|
@@ -61,8 +63,9 @@ export interface ChooseAccountInput extends RequestScope {
|
|
|
61
63
|
readonly previousAccountId?: string;
|
|
62
64
|
/**
|
|
63
65
|
* Set when the attempt this one retries was refused for a limit before any
|
|
64
|
-
* output
|
|
65
|
-
*
|
|
66
|
+
* output. The adapter should not pick `accountId` again unless it has
|
|
67
|
+
* nothing else; returning it, or `undefined`, tells the retry hook that no
|
|
68
|
+
* other account can serve, so the host's own retry decision stands.
|
|
66
69
|
*/
|
|
67
70
|
readonly rerouteFrom?: {
|
|
68
71
|
readonly accountId: string;
|
|
@@ -166,11 +169,32 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
|
|
|
166
169
|
/** Every hook is scoped to this provider; other providers are untouched. */
|
|
167
170
|
readonly providerID: string;
|
|
168
171
|
/**
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
+
* Commits an account for one attempt. An undefined answer commits nothing
|
|
173
|
+
* to routing state: no consumed retry entry, no queued choice, and no session
|
|
174
|
+
* pin created, moved or deleted. Idempotent maintenance (credential refresh
|
|
175
|
+
* to check usability and recording quota readings) is allowed. On a request,
|
|
176
|
+
* undefined stops with kind `no-account`.
|
|
177
|
+
*
|
|
178
|
+
* After a limit before any output, the retry hook makes this call itself,
|
|
179
|
+
* with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
|
|
180
|
+
* including the refused one, is kept for the next attempt of that session
|
|
181
|
+
* and kind: it does not choose again. Another account retries at once;
|
|
182
|
+
* the refused account keeps the host's decision and wait. `undefined` or a
|
|
183
|
+
* throw commits nothing: the host decides, and the next attempt chooses
|
|
184
|
+
* with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
|
|
172
185
|
*/
|
|
173
186
|
chooseAccount(input: ChooseAccountInput): Promise<string | undefined> | string | undefined;
|
|
187
|
+
/**
|
|
188
|
+
* Releases a kept retry choice that will not be used: no retry, a changed
|
|
189
|
+
* model or agent, session forgetting/deletion, disposal or record eviction.
|
|
190
|
+
* Called once with the original choose input plus its returned accountId,
|
|
191
|
+
* never for a used choice. Awaited before any later chooseAccount for the
|
|
192
|
+
* same session; errors are logged and swallowed. A model/agent change
|
|
193
|
+
* releases the old choice before choosing afresh.
|
|
194
|
+
*/
|
|
195
|
+
dropChoice?(input: ChooseAccountInput & {
|
|
196
|
+
readonly accountId: string;
|
|
197
|
+
}): Promise<void> | void;
|
|
174
198
|
/**
|
|
175
199
|
* The credential and per-account headers for an account, applied in
|
|
176
200
|
* `model.request`, `http.request` and `experimental.ws.handshake`. The last
|
|
@@ -337,7 +361,20 @@ export interface InstallOpenCode2AuthOptions {
|
|
|
337
361
|
readonly maxRecords?: number;
|
|
338
362
|
readonly logger?: OpenCode2AuthLogger;
|
|
339
363
|
}
|
|
340
|
-
|
|
364
|
+
/**
|
|
365
|
+
* Why the retry hook decided as it did:
|
|
366
|
+
*
|
|
367
|
+
* - `reroute`: refused for a limit before any output, and `chooseAccount`
|
|
368
|
+
* named another account for the next attempt, so the host retries at once;
|
|
369
|
+
* - `output-started`: output had reached the user, so no retry;
|
|
370
|
+
* - `no-account`: the attempt had no account, so no retry;
|
|
371
|
+
* - `host-decides-last-account`: refused for a limit before any output, but
|
|
372
|
+
* no other account can serve the next attempt, so the host's own decision
|
|
373
|
+
* (its wait, or its refusal to retry) stands and the next attempt may go
|
|
374
|
+
* to the refused account again;
|
|
375
|
+
* - `host-decides`: no limit was recognised, so the host's decision stands.
|
|
376
|
+
*/
|
|
377
|
+
export type RetryReason = 'reroute' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
|
|
341
378
|
/**
|
|
342
379
|
* The hook that picked an account. Normally `model.request`; a transport hook
|
|
343
380
|
* picks only when the host skipped `model.request` for that request, which a
|
package/dist/setup/enroll.d.ts
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
1
1
|
import { type MenuTerminal } from '../auth-menu/terminal.js';
|
|
2
2
|
import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
|
|
3
|
+
/** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
|
|
4
|
+
export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
|
|
5
|
+
/**
|
|
6
|
+
* The longest setup waits, in total, for the vault to create the enrollment
|
|
7
|
+
* request and for an operator to approve it. It matches the wait setup always
|
|
8
|
+
* had (300 one-second polls), but is now measured on the clock: a vault that
|
|
9
|
+
* answers each request slowly can no longer stretch it.
|
|
10
|
+
*/
|
|
11
|
+
export declare const ENROLLMENT_WAIT_MS = 300000;
|
|
12
|
+
/** Why a host's enrollment ended without a token. */
|
|
13
|
+
export type HostNotEnrolledReason = 'connection-failed' | 'unsupported-vault' | 'request-not-created' | 'approval-pending' | 'refused' | 'invalid-request' | 'incomplete';
|
|
3
14
|
/**
|
|
4
15
|
* Thrown when the enrollment ended without writing the host's token: the vault
|
|
5
|
-
* could not be reached, it
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
16
|
+
* could not be reached, it cannot enroll plugins, it refused the request, it
|
|
17
|
+
* never created one, approval never came before setup stopped waiting, or
|
|
18
|
+
* the enrollment failed in some other way (`incomplete`).
|
|
19
|
+
* Setup can then report the host as not connected without reading its files.
|
|
20
|
+
* The message is fixed text built only from vetted values, never from what
|
|
21
|
+
* the vault or client threw. `lastErrorCode` is the last enrollment error code
|
|
22
|
+
* setup saw, from the vault or from the client's transport (for example
|
|
23
|
+
* `transport_error`), for diagnostics; it carries no secret.
|
|
9
24
|
*/
|
|
10
25
|
export declare class HostNotEnrolledError extends Error {
|
|
26
|
+
readonly reason: HostNotEnrolledReason;
|
|
27
|
+
readonly lastErrorCode?: string;
|
|
28
|
+
constructor(message: string, details: {
|
|
29
|
+
reason: HostNotEnrolledReason;
|
|
30
|
+
lastErrorCode?: string;
|
|
31
|
+
});
|
|
11
32
|
}
|
|
12
33
|
/** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
|
|
13
34
|
export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<void>;
|
package/dist/setup/enroll.js
CHANGED
|
@@ -1,17 +1,53 @@
|
|
|
1
1
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
2
|
import { writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
|
|
3
3
|
import { printLine } from '../auth-menu/terminal.js';
|
|
4
|
-
import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, } from '../claustrum/enrollment.js';
|
|
4
|
+
import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, UNSUPPORTED_ENROLLMENT_CODE, } from '../claustrum/enrollment.js';
|
|
5
5
|
import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
|
|
6
6
|
const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
|
|
7
|
+
/** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
|
|
8
|
+
export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
|
|
9
|
+
/**
|
|
10
|
+
* The longest setup waits, in total, for the vault to create the enrollment
|
|
11
|
+
* request and for an operator to approve it. It matches the wait setup always
|
|
12
|
+
* had (300 one-second polls), but is now measured on the clock: a vault that
|
|
13
|
+
* answers each request slowly can no longer stretch it.
|
|
14
|
+
*/
|
|
15
|
+
export const ENROLLMENT_WAIT_MS = 300_000;
|
|
16
|
+
/** The pause between polls while a created request waits for approval. */
|
|
17
|
+
const APPROVAL_POLL_MS = 1000;
|
|
18
|
+
/**
|
|
19
|
+
* Pauses between proposals the vault failed to accept for a reason worth
|
|
20
|
+
* retrying; the last value repeats until the overall wait runs out.
|
|
21
|
+
*/
|
|
22
|
+
const PROPOSE_BACKOFF_MS = [1000, 2000, 4000, 8000, 16_000, 30_000];
|
|
23
|
+
/** Vault codes are short snake_case words; anything else is shown as `unknown`. */
|
|
24
|
+
function safeCode(code) {
|
|
25
|
+
return code && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : 'unknown';
|
|
26
|
+
}
|
|
7
27
|
/**
|
|
8
28
|
* Thrown when the enrollment ended without writing the host's token: the vault
|
|
9
|
-
* could not be reached, it
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
29
|
+
* could not be reached, it cannot enroll plugins, it refused the request, it
|
|
30
|
+
* never created one, approval never came before setup stopped waiting, or
|
|
31
|
+
* the enrollment failed in some other way (`incomplete`).
|
|
32
|
+
* Setup can then report the host as not connected without reading its files.
|
|
33
|
+
* The message is fixed text built only from vetted values, never from what
|
|
34
|
+
* the vault or client threw. `lastErrorCode` is the last enrollment error code
|
|
35
|
+
* setup saw, from the vault or from the client's transport (for example
|
|
36
|
+
* `transport_error`), for diagnostics; it carries no secret.
|
|
13
37
|
*/
|
|
14
38
|
export class HostNotEnrolledError extends Error {
|
|
39
|
+
reason;
|
|
40
|
+
lastErrorCode;
|
|
41
|
+
constructor(message, details) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = 'HostNotEnrolledError';
|
|
44
|
+
this.reason = details.reason;
|
|
45
|
+
if (details.lastErrorCode !== undefined)
|
|
46
|
+
this.lastErrorCode = safeCode(details.lastErrorCode);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function approveCommand(requestId, name) {
|
|
50
|
+
return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
|
|
15
51
|
}
|
|
16
52
|
/** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
|
|
17
53
|
export async function connectSetupHost(plugin, host, io, terminal, fence) {
|
|
@@ -22,59 +58,105 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
|
|
|
22
58
|
connectionFile: plugin.vault.connectionFile,
|
|
23
59
|
handshakeTimeoutMs: 2000,
|
|
24
60
|
}).catch(() => {
|
|
25
|
-
throw new HostNotEnrolledError('Claustrum connection failed; start ck and rerun setup.');
|
|
61
|
+
throw new HostNotEnrolledError('Claustrum connection failed; start ck and rerun setup.', { reason: 'connection-failed' });
|
|
26
62
|
});
|
|
63
|
+
const now = io.now ?? (() => performance.now());
|
|
64
|
+
const wait = io.wait ?? delay;
|
|
27
65
|
try {
|
|
28
66
|
const manager = new ClaustrumEnrollmentManager({
|
|
29
67
|
proposedName: name,
|
|
30
68
|
paths,
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
enrollPoll: async (input) => {
|
|
37
|
-
await fence();
|
|
38
|
-
return client.enrollPoll(input);
|
|
39
|
-
},
|
|
40
|
-
},
|
|
69
|
+
// Each tick of the wait below checks the fence once, just before
|
|
70
|
+
// reconcile proposes or polls. Checking again inside every vault call
|
|
71
|
+
// doubled the process listings per tick, and on Windows each listing
|
|
72
|
+
// starts PowerShell.
|
|
73
|
+
client,
|
|
41
74
|
writeTokenFile: async (path, file) => {
|
|
75
|
+
// Writing the token is what connects the host: check once more.
|
|
42
76
|
await fence();
|
|
43
77
|
await writeEnrollmentTokenFile(path, file);
|
|
44
78
|
},
|
|
45
79
|
});
|
|
80
|
+
printLine(terminal, `Asking the vault to connect ${name}…`);
|
|
81
|
+
const deadline = now() + ENROLLMENT_WAIT_MS;
|
|
46
82
|
let printedRequest;
|
|
47
|
-
|
|
83
|
+
let lastCode;
|
|
84
|
+
let reportedCode;
|
|
85
|
+
let failedProposals = 0;
|
|
86
|
+
for (;;) {
|
|
48
87
|
await fence();
|
|
49
88
|
const status = await manager.reconcile();
|
|
50
89
|
if (status.state === 'approved') {
|
|
51
90
|
printLine(terminal, `Connected ${host} to Claustrum.`);
|
|
52
91
|
return;
|
|
53
92
|
}
|
|
93
|
+
if (status.state === 'unavailable' &&
|
|
94
|
+
status.code === UNSUPPORTED_ENROLLMENT_CODE)
|
|
95
|
+
throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
|
|
96
|
+
reason: 'unsupported-vault',
|
|
97
|
+
lastErrorCode: status.code,
|
|
98
|
+
});
|
|
54
99
|
if (status.state !== 'pending' && status.state !== 'busy')
|
|
55
|
-
throw new HostNotEnrolledError('Claustrum enrollment refused; inspect its status with ck before rerunning setup.'
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
100
|
+
throw new HostNotEnrolledError('Claustrum enrollment refused; inspect its status with ck before rerunning setup.', {
|
|
101
|
+
reason: 'refused',
|
|
102
|
+
...('code' in status && { lastErrorCode: status.code }),
|
|
103
|
+
});
|
|
104
|
+
let pause = APPROVAL_POLL_MS;
|
|
105
|
+
if (status.state === 'busy')
|
|
106
|
+
lastCode = 'busy';
|
|
107
|
+
else if (status.retryCode)
|
|
108
|
+
lastCode = status.retryCode;
|
|
109
|
+
if (status.state === 'pending' && status.requestId) {
|
|
110
|
+
failedProposals = 0;
|
|
111
|
+
if (status.requestId !== printedRequest) {
|
|
112
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
|
|
113
|
+
throw new HostNotEnrolledError('Invalid enrollment request id.', {
|
|
114
|
+
reason: 'invalid-request',
|
|
115
|
+
});
|
|
116
|
+
printedRequest = status.requestId;
|
|
117
|
+
printLine(terminal, 'Waiting for approval. In another terminal, run:');
|
|
118
|
+
printLine(terminal, ` ${approveCommand(status.requestId, name)}`);
|
|
119
|
+
printLine(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
|
|
120
|
+
}
|
|
65
121
|
}
|
|
66
|
-
|
|
122
|
+
else if (status.state === 'pending' && status.retryCode) {
|
|
123
|
+
// No request id came back. Back off instead of asking
|
|
124
|
+
// again every second, and say so once per distinct code.
|
|
125
|
+
pause =
|
|
126
|
+
PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
|
|
127
|
+
failedProposals++;
|
|
128
|
+
const code = safeCode(status.retryCode);
|
|
129
|
+
if (code !== reportedCode) {
|
|
130
|
+
reportedCode = code;
|
|
131
|
+
printLine(terminal, `The vault has not created the request yet (${code}); retrying.`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const remaining = deadline - now();
|
|
135
|
+
if (remaining <= 0)
|
|
136
|
+
break;
|
|
137
|
+
await wait(Math.min(pause, remaining));
|
|
67
138
|
}
|
|
68
|
-
|
|
139
|
+
if (printedRequest)
|
|
140
|
+
throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
|
|
141
|
+
reason: 'approval-pending',
|
|
142
|
+
...(lastCode !== undefined && { lastErrorCode: lastCode }),
|
|
143
|
+
});
|
|
144
|
+
const code = safeCode(lastCode);
|
|
145
|
+
throw new HostNotEnrolledError(`The vault never created the enrollment request (last error: ${code}). Check that ck is running, then rerun setup.`, { reason: 'request-not-created', lastErrorCode: code });
|
|
69
146
|
}
|
|
70
147
|
catch (error) {
|
|
71
148
|
if (error instanceof ProcessFenceViolationError ||
|
|
72
|
-
error instanceof ProcessInspectionError
|
|
149
|
+
error instanceof ProcessInspectionError ||
|
|
150
|
+
// Built above from fixed text and vetted values only.
|
|
151
|
+
error instanceof HostNotEnrolledError)
|
|
73
152
|
throw error;
|
|
74
|
-
// Enrollment exceptions can carry request secrets or bearer tokens; never
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
throw new
|
|
153
|
+
// Enrollment exceptions can carry request secrets or bearer tokens; never
|
|
154
|
+
// display them. Only a vetted error code goes into the diagnostics.
|
|
155
|
+
const code = error?.code;
|
|
156
|
+
throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
|
|
157
|
+
reason: 'incomplete',
|
|
158
|
+
...(typeof code === 'string' && { lastErrorCode: code }),
|
|
159
|
+
});
|
|
78
160
|
}
|
|
79
161
|
finally {
|
|
80
162
|
client.close();
|
package/dist/setup/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
|
|
2
2
|
export { SetupCommandError, setupEnrollment } from './command-error.js';
|
|
3
3
|
export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
|
|
4
|
+
export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, type HostNotEnrolledReason, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
|
|
4
5
|
export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
|
|
5
6
|
export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
|
|
6
7
|
export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
|
package/dist/setup/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
|
|
2
2
|
export { SetupCommandError, setupEnrollment } from './command-error.js';
|
|
3
3
|
export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
|
|
4
|
+
export { ENROLLMENT_WAIT_MS, HostNotEnrolledError, UNSUPPORTED_VAULT_MESSAGE, } from './enroll.js';
|
|
4
5
|
export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
|
|
5
6
|
export { planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
|