@thinkrun/cli 0.1.39 → 0.1.40
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/scripts/browse.sh +40 -7
- package/dist/shared/group-binding-key.d.ts +5 -0
- package/dist/shared/group-binding-key.js +15 -0
- package/dist/shared/group-binding-key.test.js +50 -0
- package/dist/shared/native-type-budget.d.ts +16 -0
- package/dist/shared/native-type-budget.js +28 -0
- package/dist/shared/onboarding-drips.d.ts +13 -0
- package/dist/shared/onboarding-drips.js +100 -0
- package/dist/src/adapters/cloud.d.ts +2 -0
- package/dist/src/adapters/cloud.d.ts.map +1 -1
- package/dist/src/adapters/cloud.js +112 -17
- package/dist/src/adapters/cloud.js.map +1 -1
- package/dist/src/adapters/index.d.ts.map +1 -1
- package/dist/src/adapters/index.js +30 -5
- package/dist/src/adapters/index.js.map +1 -1
- package/dist/src/adapters/local.d.ts +2 -0
- package/dist/src/adapters/local.d.ts.map +1 -1
- package/dist/src/adapters/local.js +23 -8
- package/dist/src/adapters/local.js.map +1 -1
- package/dist/src/commands/actions.d.ts.map +1 -1
- package/dist/src/commands/actions.js +13 -15
- package/dist/src/commands/actions.js.map +1 -1
- package/dist/src/commands/analyze.d.ts.map +1 -1
- package/dist/src/commands/analyze.js +29 -1
- package/dist/src/commands/analyze.js.map +1 -1
- package/dist/src/commands/cloud.d.ts.map +1 -1
- package/dist/src/commands/cloud.js +3 -1
- package/dist/src/commands/cloud.js.map +1 -1
- package/dist/src/commands/evaluate-helpers.d.ts.map +1 -1
- package/dist/src/commands/evaluate-helpers.js +10 -2
- package/dist/src/commands/evaluate-helpers.js.map +1 -1
- package/dist/src/local-bridge-timing.d.ts +3 -0
- package/dist/src/local-bridge-timing.d.ts.map +1 -1
- package/dist/src/local-bridge-timing.js +3 -0
- package/dist/src/local-bridge-timing.js.map +1 -1
- package/dist/src/types.d.ts +3 -1
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/utils.d.ts +9 -3
- package/dist/src/utils.d.ts.map +1 -1
- package/dist/src/utils.js +24 -3
- package/dist/src/utils.js.map +1 -1
- package/dist/src/working-location.d.ts +1 -1
- package/dist/src/working-location.d.ts.map +1 -1
- package/dist/src/working-location.js +89 -67
- package/dist/src/working-location.js.map +1 -1
- package/package.json +2 -2
package/dist/scripts/browse.sh
CHANGED
|
@@ -554,24 +554,57 @@ case "${1:-help}" in
|
|
|
554
554
|
echo "$RESP" >&2
|
|
555
555
|
exit 1
|
|
556
556
|
fi
|
|
557
|
-
#
|
|
558
|
-
|
|
559
|
-
|
|
557
|
+
# Each status GET and sleep consumes the same 120s elapsed-seconds budget.
|
|
558
|
+
READY_TIMEOUT_SECONDS=120
|
|
559
|
+
READY_MAX_POLLS=40
|
|
560
|
+
READY_SLEEP_SECONDS=3
|
|
561
|
+
READY_STARTED_SECONDS=$SECONDS
|
|
562
|
+
for i in $(seq 1 "$READY_MAX_POLLS"); do
|
|
563
|
+
READY_ELAPSED_SECONDS=$((SECONDS - READY_STARTED_SECONDS))
|
|
564
|
+
READY_REMAINING_SECONDS=$((READY_TIMEOUT_SECONDS - READY_ELAPSED_SECONDS))
|
|
565
|
+
if [ "$READY_REMAINING_SECONDS" -le 0 ]; then
|
|
566
|
+
break
|
|
567
|
+
fi
|
|
568
|
+
REQUEST_TIMEOUT_SECONDS="$READY_REMAINING_SECONDS"
|
|
569
|
+
STATUS_RESPONSE=$(curl -s --max-time "$REQUEST_TIMEOUT_SECONDS" "${H[@]}" \
|
|
570
|
+
"$BASE/api/sessions/$SID" 2>/dev/null || true)
|
|
571
|
+
READY_ELAPSED_SECONDS=$((SECONDS - READY_STARTED_SECONDS))
|
|
572
|
+
if [ "$READY_ELAPSED_SECONDS" -ge "$READY_TIMEOUT_SECONDS" ]; then
|
|
573
|
+
break
|
|
574
|
+
fi
|
|
575
|
+
CANONICAL_SESSION=$(printf '%s' "$STATUS_RESPONSE" | jq -cse 'if length != 1 then {} else .[0] as $root | if ($root | type) != "object" or $root.success == false then {} elif ($root | has("data")) then (if ($root.data | type) == "object" then $root.data else {} end) else $root end end' 2>/dev/null) || CANONICAL_SESSION='{}'
|
|
576
|
+
STATUS=$(printf '%s' "$CANONICAL_SESSION" | jq -r 'if (.status | type) == "string" then .status else "unknown" end' 2>/dev/null) || STATUS="unknown"
|
|
577
|
+
BROWSER_READY=$(printf '%s' "$CANONICAL_SESSION" | jq -r 'if (.browserReady | type) == "boolean" then (.browserReady | tostring) else "missing" end' 2>/dev/null) || BROWSER_READY="missing"
|
|
560
578
|
case "$STATUS" in
|
|
561
579
|
ready|active|running)
|
|
562
|
-
|
|
563
|
-
|
|
580
|
+
if [ "$BROWSER_READY" = "true" ]; then
|
|
581
|
+
echo "$SID"
|
|
582
|
+
exit 0
|
|
583
|
+
fi
|
|
584
|
+
printf "." >&2
|
|
564
585
|
;;
|
|
565
586
|
creating|provisioning|pending)
|
|
566
587
|
printf "." >&2
|
|
567
|
-
sleep 3
|
|
568
588
|
;;
|
|
569
|
-
failed|error|terminated)
|
|
589
|
+
failed|error|terminated|closed|completed|cancelled)
|
|
570
590
|
echo "" >&2
|
|
571
591
|
echo "ERROR: Session $SID failed with status: $STATUS" >&2
|
|
572
592
|
exit 1
|
|
573
593
|
;;
|
|
594
|
+
*)
|
|
595
|
+
printf "." >&2
|
|
596
|
+
;;
|
|
574
597
|
esac
|
|
598
|
+
READY_ELAPSED_SECONDS=$((SECONDS - READY_STARTED_SECONDS))
|
|
599
|
+
READY_REMAINING_SECONDS=$((READY_TIMEOUT_SECONDS - READY_ELAPSED_SECONDS))
|
|
600
|
+
if [ "$READY_REMAINING_SECONDS" -le 0 ]; then
|
|
601
|
+
break
|
|
602
|
+
fi
|
|
603
|
+
SLEEP_SECONDS="$READY_SLEEP_SECONDS"
|
|
604
|
+
if [ "$READY_REMAINING_SECONDS" -lt "$SLEEP_SECONDS" ]; then
|
|
605
|
+
SLEEP_SECONDS="$READY_REMAINING_SECONDS"
|
|
606
|
+
fi
|
|
607
|
+
sleep "$SLEEP_SECONDS"
|
|
575
608
|
done
|
|
576
609
|
echo "" >&2
|
|
577
610
|
echo "ERROR: Session $SID not ready after 120s" >&2
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Return a collision-resistant filesystem key for a caller-provided group name. */
|
|
2
|
+
export declare function getGroupBindingKey(group: string): string;
|
|
3
|
+
|
|
4
|
+
/** Return the historical key for read-only legacy lookup and safe cleanup. */
|
|
5
|
+
export declare function getLegacyGroupBindingKey(group: string): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const GROUP_KEY_STEM_LIMIT = 64;
|
|
4
|
+
|
|
5
|
+
/** Return a collision-resistant filesystem key for a caller-provided group name. */
|
|
6
|
+
export function getGroupBindingKey(group) {
|
|
7
|
+
const stem = group.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, GROUP_KEY_STEM_LIMIT);
|
|
8
|
+
const digest = createHash('sha256').update(Buffer.from(group, 'utf16le')).digest('hex');
|
|
9
|
+
return `${stem}~${digest}`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Return the historical key for read-only legacy lookup and safe cleanup. */
|
|
13
|
+
export function getLegacyGroupBindingKey(group) {
|
|
14
|
+
return group.replace(/[^A-Za-z0-9_-]/g, '_') || 'default';
|
|
15
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { getGroupBindingKey, getLegacyGroupBindingKey } from './group-binding-key.js';
|
|
4
|
+
|
|
5
|
+
describe('group binding keys', () => {
|
|
6
|
+
test('puts every name in a bounded hashed namespace', () => {
|
|
7
|
+
for (const group of ['agent_42-team', 'a'.repeat(240), 'a'.repeat(241)]) {
|
|
8
|
+
const key = getGroupBindingKey(group);
|
|
9
|
+
expect(key).not.toBe(group);
|
|
10
|
+
expect(key).toMatch(/^[A-Za-z0-9_-]*~[a-f0-9]{64}$/);
|
|
11
|
+
expect(key.length).toBeLessThanOrEqual(129);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test('case-folding variants get distinct keys on case-insensitive filesystems', () => {
|
|
16
|
+
const keys = ['Team', 'team', 'TEAM'].map(getGroupBindingKey);
|
|
17
|
+
expect(new Set(keys).size).toBe(3);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('Windows device basenames are hashed into valid non-device filenames', () => {
|
|
21
|
+
for (const group of ['con', 'prn', 'aux', 'nul', 'com1', 'com9', 'lpt1', 'lpt9']) {
|
|
22
|
+
const key = getGroupBindingKey(group);
|
|
23
|
+
expect(key).not.toBe(group);
|
|
24
|
+
expect(key).toMatch(/^[a-z0-9_-]*~[a-f0-9]{64}$/);
|
|
25
|
+
expect(key).not.toMatch(/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('separates names that collided under the historical sanitizer', () => {
|
|
30
|
+
expect(getLegacyGroupBindingKey('a b')).toBe(getLegacyGroupBindingKey('a_b'));
|
|
31
|
+
expect(getGroupBindingKey('a b')).not.toBe(getGroupBindingKey('a_b'));
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test('hashes Unicode and lone surrogate code units distinctly within the path bound', () => {
|
|
35
|
+
for (const group of ['研究', '\uD800', '\uDC00', 'x'.repeat(400) + ' /unsafe']) {
|
|
36
|
+
const key = getGroupBindingKey(group);
|
|
37
|
+
const expectedHash = createHash('sha256').update(Buffer.from(group, 'utf16le')).digest('hex');
|
|
38
|
+
expect(key.endsWith(`~${expectedHash}`)).toBe(true);
|
|
39
|
+
expect(key.length).toBeLessThanOrEqual(129);
|
|
40
|
+
expect(key).toMatch(/^[A-Za-z0-9_-]*~[a-f0-9]{64}$/);
|
|
41
|
+
}
|
|
42
|
+
expect(getGroupBindingKey('\uD800')).not.toBe(getGroupBindingKey('\uDC00'));
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('empty input hashes independently of the legacy default alias', () => {
|
|
46
|
+
expect(getLegacyGroupBindingKey('')).toBe('default');
|
|
47
|
+
expect(getGroupBindingKey('')).not.toBe('default');
|
|
48
|
+
expect(getGroupBindingKey('')).toMatch(/^~[a-f0-9]{64}$/);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const NATIVE_TYPE_EXECUTION_BUFFER_MS: 5000;
|
|
2
|
+
export declare const NATIVE_TYPE_MAX_TIMEOUT_MS: 600000;
|
|
3
|
+
|
|
4
|
+
export interface NativeTypeBudget {
|
|
5
|
+
characterCount: number;
|
|
6
|
+
delayMs: number;
|
|
7
|
+
requiredTimeoutMs: number;
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
exceedsLimit: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export declare function getNativeTypeBudget(
|
|
13
|
+
text: string,
|
|
14
|
+
delay: number | undefined,
|
|
15
|
+
defaultTimeoutMs: number,
|
|
16
|
+
): NativeTypeBudget;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const NATIVE_TYPE_EXECUTION_BUFFER_MS = 5_000;
|
|
2
|
+
export const NATIVE_TYPE_MAX_TIMEOUT_MS = 600_000;
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compute the native host's typing command timeout without dispatching it.
|
|
6
|
+
* Character count follows Unicode code points, matching Array.from(text).
|
|
7
|
+
*/
|
|
8
|
+
export function getNativeTypeBudget(text, delay, defaultTimeoutMs) {
|
|
9
|
+
const characterCount = Array.from(text).length;
|
|
10
|
+
const normalizedDelayMs = typeof delay === 'number' && Number.isFinite(delay) && delay > 0
|
|
11
|
+
? delay
|
|
12
|
+
: 0;
|
|
13
|
+
const requiredTimeoutMs = Math.ceil(
|
|
14
|
+
characterCount * normalizedDelayMs + NATIVE_TYPE_EXECUTION_BUFFER_MS,
|
|
15
|
+
);
|
|
16
|
+
const timeoutMs = Math.min(
|
|
17
|
+
NATIVE_TYPE_MAX_TIMEOUT_MS,
|
|
18
|
+
Math.max(defaultTimeoutMs, requiredTimeoutMs),
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
characterCount,
|
|
23
|
+
delayMs: normalizedDelayMs,
|
|
24
|
+
requiredTimeoutMs,
|
|
25
|
+
timeoutMs,
|
|
26
|
+
exceedsLimit: requiredTimeoutMs > NATIVE_TYPE_MAX_TIMEOUT_MS,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const LEDGER_DDL: string;
|
|
2
|
+
export interface OnboardingEnv { [key: string]: string | undefined }
|
|
3
|
+
export type Sql = (query: string, parameters?: readonly unknown[]) => Promise<any[]>;
|
|
4
|
+
export function onboardingConfig(env: OnboardingEnv): { since: string; sequenceId: string; version: number; recipients: string[] | null } | null;
|
|
5
|
+
export interface OnboardingSdk {
|
|
6
|
+
enroll(input: { sequenceId: string; version: number; subjectId: string; email: string; consent: true }): Promise<{ data: { id: string } }>;
|
|
7
|
+
getEnrollment(id: string): Promise<{ data: { status: string } }>;
|
|
8
|
+
track(input: { id: string; subjectId: string; name: string }): Promise<unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface SqlDatabase { executeQuery(query: { sql: string; parameters: readonly unknown[]; query: { kind: 'RawNode'; sqlFragments: string[]; parameters: unknown[] } }): Promise<{ rows: any[] }> }
|
|
11
|
+
export function onboardingSql(env: OnboardingEnv, createMechKysely: (options: { appId: string; apiKey: string }) => SqlDatabase): Sql;
|
|
12
|
+
export function queueVerifiedSignup(env: OnboardingEnv, subjectId: string, execute: (env: OnboardingEnv) => Sql): Promise<void>;
|
|
13
|
+
export function pumpOnboarding(options: { env: OnboardingEnv; sql: Sql; sdk: OnboardingSdk; completedTask: (subjectId: string, since: string) => Promise<boolean>; limit?: number }): Promise<{ enrolled: number; activated: number; failed: number }>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Specialized delivery ledger for this one onboarding sequence. No runtime DDL.
|
|
2
|
+
export const LEDGER_DDL = `CREATE TABLE circleinbox_onboarding (
|
|
3
|
+
subject_id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
|
4
|
+
enrollment_id TEXT, enrolled_at TIMESTAMPTZ, activated_at TIMESTAMPTZ, finished_at TIMESTAMPTZ,
|
|
5
|
+
checked_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
6
|
+
)`;
|
|
7
|
+
|
|
8
|
+
export function onboardingConfig(env) {
|
|
9
|
+
if (env.CIRCLEINBOX_ONBOARDING_ENABLED !== 'true') return null;
|
|
10
|
+
const since = new Date(env.CIRCLEINBOX_ONBOARDING_SINCE || '');
|
|
11
|
+
if (!Number.isFinite(since.getTime()) || env.CIRCLEINBOX_ONBOARDING_CONSENT !== 'true') {
|
|
12
|
+
throw new Error('Onboarding requires an explicit enable timestamp and consent assertion');
|
|
13
|
+
}
|
|
14
|
+
if (!env.CIRCLEINBOX_API_KEY || !Number.isSafeInteger(Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION)) || Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION) < 1) {
|
|
15
|
+
throw new Error('Onboarding requires credentials and a published sequence version');
|
|
16
|
+
}
|
|
17
|
+
const allowAll = env.CIRCLEINBOX_ONBOARDING_ALLOW_ALL_NEW_USERS === 'true';
|
|
18
|
+
const raw = env.CIRCLEINBOX_ONBOARDING_RECIPIENT_ALLOWLIST?.trim() || '';
|
|
19
|
+
if (allowAll === Boolean(raw) || raw.length > 5100) throw new Error('Onboarding requires exactly one recipient scope');
|
|
20
|
+
const recipients = raw ? [...new Set(raw.split(',').map((email) => email.trim().toLowerCase()))] : null;
|
|
21
|
+
if (recipients && (recipients.length > 20 || recipients.some((email) => email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)))) {
|
|
22
|
+
throw new Error('Onboarding recipient allowlist must contain 1 to 20 valid emails');
|
|
23
|
+
}
|
|
24
|
+
return { since: since.toISOString(), sequenceId: 'thinkrun-onboarding', version: Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION), recipients };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function onboardingSql(env, createMechKysely) {
|
|
28
|
+
const db = createMechKysely({ appId: env.MECH_APP_ID || env.MECH_BROWSE_APP_ID || '', apiKey: env.MECH_API_KEY });
|
|
29
|
+
return async (sql, parameters = []) => {
|
|
30
|
+
// executeQuery accepts this CompiledQuery directly; SQL is already compiled and bound.
|
|
31
|
+
const result = await db.executeQuery({ sql, parameters, query: { kind: 'RawNode', sqlFragments: [sql], parameters: [] } });
|
|
32
|
+
return result.rows;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function queueVerifiedSignup(env, subjectId, execute) {
|
|
37
|
+
const config = onboardingConfig(env);
|
|
38
|
+
if (!config) return;
|
|
39
|
+
const sql = execute(env);
|
|
40
|
+
// A successful verification is the source of truth; do not trust request email.
|
|
41
|
+
await sql(`INSERT INTO circleinbox_onboarding (subject_id,email)
|
|
42
|
+
SELECT id::text,email FROM users WHERE id=$1 AND email_verified=true AND created_at >= $2::timestamptz
|
|
43
|
+
AND ($3::text[] IS NULL OR lower(email)=ANY($3::text[]))
|
|
44
|
+
ON CONFLICT (subject_id) DO NOTHING`, [subjectId, config.since, config.recipients]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function pumpOnboarding({ env, sql, sdk, completedTask, limit = 25 }) {
|
|
48
|
+
const config = onboardingConfig(env);
|
|
49
|
+
if (!config) return { enrolled: 0, activated: 0, failed: 0 };
|
|
50
|
+
// Commit queued ledger rows BEFORE any remote SDK call, even during an outage.
|
|
51
|
+
// Exclude every queued subject (including enrolled_at=null); the next pass can
|
|
52
|
+
// discover users beyond this batch while earlier deliveries remain pending.
|
|
53
|
+
// This closes the post-auth enqueue gap for newly created verified accounts.
|
|
54
|
+
await sql(`INSERT INTO circleinbox_onboarding (subject_id,email)
|
|
55
|
+
SELECT u.id::text,u.email FROM users u WHERE u.email_verified=true AND u.created_at >= $1::timestamptz
|
|
56
|
+
AND ($2::text[] IS NULL OR lower(u.email)=ANY($2::text[]))
|
|
57
|
+
AND NOT EXISTS (SELECT 1 FROM circleinbox_onboarding o WHERE o.subject_id=u.id::text)
|
|
58
|
+
ORDER BY u.created_at,u.id LIMIT 100 ON CONFLICT (subject_id) DO NOTHING`, [config.since, config.recipients]);
|
|
59
|
+
const rows = await sql(`SELECT subject_id,email,enrolled_at,enrollment_id FROM circleinbox_onboarding
|
|
60
|
+
WHERE activated_at IS NULL AND finished_at IS NULL
|
|
61
|
+
AND ($2::text[] IS NULL OR lower(email)=ANY($2::text[]))
|
|
62
|
+
ORDER BY checked_at,subject_id LIMIT $1`, [limit, config.recipients]);
|
|
63
|
+
const result = { enrolled: 0, activated: 0, failed: 0 };
|
|
64
|
+
for (const row of rows) {
|
|
65
|
+
let failed = false;
|
|
66
|
+
try {
|
|
67
|
+
let enrollmentId = row.enrollment_id;
|
|
68
|
+
if (!row.enrolled_at || !enrollmentId) {
|
|
69
|
+
// API contract: UNIQUE(org,sequenceId,subjectId) across versions. Identical
|
|
70
|
+
// enroll replays return the same resource; changed payloads return409.
|
|
71
|
+
// Replaying after a lost ledger acknowledgment cannot create another workflow.
|
|
72
|
+
const enrollment = await sdk.enroll({ sequenceId: config.sequenceId, version: config.version, subjectId: row.subject_id, email: row.email, consent: true });
|
|
73
|
+
enrollmentId = enrollment?.data?.id;
|
|
74
|
+
if (typeof enrollmentId !== 'string' || !enrollmentId) throw new Error('InvalidEnrollmentResponse');
|
|
75
|
+
await sql('UPDATE circleinbox_onboarding SET enrolled_at=CURRENT_TIMESTAMP,enrollment_id=$2 WHERE subject_id=$1', [row.subject_id, enrollmentId]);
|
|
76
|
+
result.enrolled++;
|
|
77
|
+
}
|
|
78
|
+
const remote = await sdk.getEnrollment(enrollmentId);
|
|
79
|
+
if (['completed', 'cancelled', 'suppressed', 'failed', 'unknown'].includes(remote?.data?.status)) {
|
|
80
|
+
await sql('UPDATE circleinbox_onboarding SET finished_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!['active', 'waiting', 'sending'].includes(remote?.data?.status)) throw new Error('InvalidEnrollmentResponse');
|
|
84
|
+
if (await completedTask(row.subject_id, config.since)) {
|
|
85
|
+
await sdk.track({ id: `thinkrun:activated:${row.subject_id}`, subjectId: row.subject_id, name: 'thinkrun.task_completed' });
|
|
86
|
+
await sql('UPDATE circleinbox_onboarding SET activated_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]);
|
|
87
|
+
result.activated++;
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
// Status remains pending; retry uses stable enrollment/event identifiers.
|
|
91
|
+
failed = true;
|
|
92
|
+
result.failed++;
|
|
93
|
+
} finally {
|
|
94
|
+
try { await sql('UPDATE circleinbox_onboarding SET checked_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]); }
|
|
95
|
+
catch { if (!failed) result.failed++; }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
@@ -9,6 +9,7 @@ export declare class CloudAdapter implements BrowserAdapter {
|
|
|
9
9
|
private defaultTimeout;
|
|
10
10
|
constructor(apiKey?: string, baseUrl?: string);
|
|
11
11
|
private request;
|
|
12
|
+
private isTransientReadFailure;
|
|
12
13
|
private sleep;
|
|
13
14
|
private getActiveSessionId;
|
|
14
15
|
/**
|
|
@@ -36,6 +37,7 @@ export declare class CloudAdapter implements BrowserAdapter {
|
|
|
36
37
|
waitForSessionReady(sessionId: string, timeout?: number): Promise<Session>;
|
|
37
38
|
stopSession(sessionId?: string): Promise<void>;
|
|
38
39
|
getSession(sessionId: string): Promise<Session>;
|
|
40
|
+
private readSession;
|
|
39
41
|
listSessions(): Promise<Session[]>;
|
|
40
42
|
listArtifacts(sessionId: string): Promise<any>;
|
|
41
43
|
navigate(url: string, options?: NavigateOptions): Promise<ActionResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloud.d.ts","sourceRoot":"","sources":["../../../src/adapters/cloud.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,cAAc,EACd,WAAW,EACX,YAAY,EACZ,aAAa,EACb,aAAa,EACd,MAAM,aAAa,CAAC;AAyBrB,qBAAa,YAAa,YAAW,cAAc;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,cAAc,CAAS;gBAEnB,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;YAuB/B,OAAO;
|
|
1
|
+
{"version":3,"file":"cloud.d.ts","sourceRoot":"","sources":["../../../src/adapters/cloud.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EACV,OAAO,EACP,cAAc,EACd,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,cAAc,EACd,WAAW,EACX,YAAY,EACZ,aAAa,EACb,aAAa,EACd,MAAM,aAAa,CAAC;AAyBrB,qBAAa,YAAa,YAAW,cAAc;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,cAAc,CAAS;gBAEnB,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,C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CAAC;IAMhC,SAAS,IAAI,OAAO,CAAC,YAAY,CAAC;IAKlC,YAAY,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IActF,kBAAkB,IAAI,OAAO,CAAC,aAAa,CAAC;IAe5C,kBAAkB,IAAI,OAAO,CAAC,aAAa,CAAC;IAe5C,SAAS,IAAI,OAAO,CAAC,YAAY,CAAC;IAWxC;;OAEG;IACG,SAAS,CACb,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,YAAY,EACtC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAChC,OAAO,CAAC,OAAO,CAAC;IAiCnB,gGAAgG;IAChG,OAAO,CAAC,qBAAqB;CAe9B"}
|
|
@@ -34,15 +34,45 @@ export class CloudAdapter {
|
|
|
34
34
|
}
|
|
35
35
|
async request(path, options = {}, retries = 3) {
|
|
36
36
|
const url = `${this.baseUrl}${path}`;
|
|
37
|
+
const method = (options.method || 'GET').toUpperCase();
|
|
38
|
+
const canRetry = method === 'GET' || method === 'HEAD';
|
|
37
39
|
const headers = {
|
|
38
40
|
'Content-Type': 'application/json',
|
|
39
41
|
'x-api-key': this.apiKey,
|
|
40
42
|
...options.headers,
|
|
41
43
|
};
|
|
42
|
-
const
|
|
44
|
+
const bodyTimeout = (() => {
|
|
45
|
+
if (!options.body)
|
|
46
|
+
return undefined;
|
|
47
|
+
try {
|
|
48
|
+
const body = JSON.parse(options.body);
|
|
49
|
+
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
50
|
+
return undefined;
|
|
51
|
+
const timeout = body.timeout;
|
|
52
|
+
return typeof timeout === 'number' && Number.isFinite(timeout) && timeout > 0
|
|
53
|
+
? timeout
|
|
54
|
+
: undefined;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
})();
|
|
60
|
+
// Match MCP's caller budget: callers may specify a browser-action timeout
|
|
61
|
+
// in the JSON body, while an explicit transport timeout (for example the
|
|
62
|
+
// typing and fingerprint budgets) remains authoritative.
|
|
63
|
+
const selectedFetchTimeout = options.timeoutMs ?? (bodyTimeout === undefined
|
|
64
|
+
? this.defaultTimeout
|
|
65
|
+
: Math.min(615_000, Math.max(this.defaultTimeout, bodyTimeout + 15_000)));
|
|
66
|
+
// Node's AbortSignal.timeout requires an integer, whereas Bun accepts a
|
|
67
|
+
// fractional duration. Round valid budgets up so both runtimes can carry
|
|
68
|
+
// the same finite-positive caller timeout without losing milliseconds.
|
|
69
|
+
// Invalid explicit values pass through and retain AbortSignal's errors.
|
|
70
|
+
const fetchTimeout = Number.isFinite(selectedFetchTimeout) && selectedFetchTimeout >= 0
|
|
71
|
+
? Math.ceil(selectedFetchTimeout)
|
|
72
|
+
: selectedFetchTimeout;
|
|
43
73
|
try {
|
|
44
74
|
const response = await fetch(url, {
|
|
45
|
-
method
|
|
75
|
+
method,
|
|
46
76
|
headers,
|
|
47
77
|
body: options.body,
|
|
48
78
|
signal: AbortSignal.timeout(fetchTimeout),
|
|
@@ -90,7 +120,14 @@ export class CloudAdapter {
|
|
|
90
120
|
}
|
|
91
121
|
const hint = typeof data.hint === 'string' ? data.hint : undefined;
|
|
92
122
|
const errMessage = errStr || msgStr || 'API request failed';
|
|
93
|
-
|
|
123
|
+
const storageErrorIdentity = codeStr === 'STORAGE_UNAVAILABLE'
|
|
124
|
+
|| errStr === 'STORAGE_UNAVAILABLE';
|
|
125
|
+
const knownPreDispatchStorageError = !canRetry
|
|
126
|
+
&& response.status === 503
|
|
127
|
+
&& storageErrorIdentity
|
|
128
|
+
&& data.retryable === true
|
|
129
|
+
&& data.outcomeUnknown !== true;
|
|
130
|
+
throw new ApiError(errMessage, response.status, hint, knownPreDispatchStorageError ? 'STORAGE_UNAVAILABLE' : codeStr || undefined, knownPreDispatchStorageError ? true : undefined);
|
|
94
131
|
}
|
|
95
132
|
if (!text) {
|
|
96
133
|
return {};
|
|
@@ -103,18 +140,47 @@ export class CloudAdapter {
|
|
|
103
140
|
}
|
|
104
141
|
}
|
|
105
142
|
catch (error) {
|
|
106
|
-
//
|
|
107
|
-
|
|
143
|
+
// Only replay safe reads. A timed out or failed mutation may already have
|
|
144
|
+
// reached the browser, so replaying it could duplicate an action.
|
|
145
|
+
const status = error instanceof ApiError ? error.statusCode : error.status;
|
|
146
|
+
const ambiguousServerError = status === 408
|
|
147
|
+
|| (status !== undefined && status >= 500 && status <= 599);
|
|
148
|
+
const code = error?.code || error?.cause?.code;
|
|
149
|
+
const transientNetwork = code === 'ECONNRESET' || code === 'ETIMEDOUT'
|
|
150
|
+
|| error?.name === 'TimeoutError' || error?.name === 'AbortError';
|
|
151
|
+
if (canRetry && retries > 0 && this.isTransientReadFailure(error)) {
|
|
108
152
|
await this.sleep(Math.pow(2, 3 - retries) * 1000);
|
|
109
153
|
return this.request(path, options, retries - 1);
|
|
110
154
|
}
|
|
111
155
|
// Re-throw our custom errors
|
|
112
156
|
if (error instanceof ApiError || error instanceof SessionError) {
|
|
157
|
+
if (error instanceof ApiError && !canRetry && (transientNetwork || ambiguousServerError)) {
|
|
158
|
+
// The routing middleware's exact 503 STORAGE_UNAVAILABLE response
|
|
159
|
+
// guarantees pre-dispatch failure. Preserve that one structured
|
|
160
|
+
// retry signal; a generic retryable flag on a 5xx is not sufficient.
|
|
161
|
+
if (error.nativeCode === 'STORAGE_UNAVAILABLE' && error.retryable === true)
|
|
162
|
+
throw error;
|
|
163
|
+
throw new ApiError(error.message, error.statusCode, 'Check the browser/session state before retrying this command; its outcome may be unknown.', error.nativeCode, false);
|
|
164
|
+
}
|
|
113
165
|
throw error;
|
|
114
166
|
}
|
|
115
|
-
//
|
|
116
|
-
throw new ApiError(error.message || 'Network request failed', undefined,
|
|
117
|
-
|
|
167
|
+
// Network failures and timeouts leave mutation outcomes unknown.
|
|
168
|
+
throw new ApiError(error.message || 'Network request failed', undefined, canRetry
|
|
169
|
+
? 'Check your internet connection'
|
|
170
|
+
: 'Check the browser/session state before retrying this command; its outcome may be unknown.', canRetry && (error?.name === 'TimeoutError' || error?.name === 'AbortError')
|
|
171
|
+
? error.name
|
|
172
|
+
: code, canRetry ? undefined : false);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
isTransientReadFailure(error) {
|
|
176
|
+
const candidate = error;
|
|
177
|
+
if (!candidate)
|
|
178
|
+
return false;
|
|
179
|
+
const status = candidate instanceof ApiError ? candidate.statusCode : candidate.status ?? candidate.statusCode;
|
|
180
|
+
const transientCodes = [candidate.nativeCode, candidate.code, candidate.cause?.code];
|
|
181
|
+
return status === 502 || status === 503
|
|
182
|
+
|| transientCodes.some((code) => code === 'ECONNRESET' || code === 'ETIMEDOUT' || code === 'TimeoutError' || code === 'AbortError')
|
|
183
|
+
|| candidate.name === 'TimeoutError' || candidate.name === 'AbortError';
|
|
118
184
|
}
|
|
119
185
|
sleep(ms) {
|
|
120
186
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
@@ -238,6 +304,12 @@ export class CloudAdapter {
|
|
|
238
304
|
status: status,
|
|
239
305
|
createdAt: new Date().toISOString(),
|
|
240
306
|
};
|
|
307
|
+
const browserReady = typeof response.browserReady === 'boolean'
|
|
308
|
+
? response.browserReady
|
|
309
|
+
: response.data?.browserReady;
|
|
310
|
+
if (typeof browserReady === 'boolean') {
|
|
311
|
+
session.browserReady = browserReady;
|
|
312
|
+
}
|
|
241
313
|
if (!setCloudSessionContext(session.sessionId)) {
|
|
242
314
|
try {
|
|
243
315
|
await this.request(`/api/sessions/${session.sessionId}`, { method: 'DELETE' });
|
|
@@ -251,17 +323,37 @@ export class CloudAdapter {
|
|
|
251
323
|
}
|
|
252
324
|
async waitForSessionReady(sessionId, timeout = 90000) {
|
|
253
325
|
const pollInterval = 2000;
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
326
|
+
const deadline = performance.now() + timeout;
|
|
327
|
+
const readyStatuses = ['active', 'ready', 'running'];
|
|
328
|
+
const terminalStatuses = ['error', 'failed', 'terminated', 'closed', 'completed', 'cancelled'];
|
|
329
|
+
while (performance.now() < deadline) {
|
|
330
|
+
const remainingMs = deadline - performance.now();
|
|
331
|
+
let session;
|
|
332
|
+
try {
|
|
333
|
+
session = await this.readSession(sessionId, remainingMs, 0);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (performance.now() >= deadline)
|
|
337
|
+
break;
|
|
338
|
+
if (this.isTransientReadFailure(error)) {
|
|
339
|
+
const sleepMs = Math.min(pollInterval, Math.max(0, deadline - performance.now()));
|
|
340
|
+
if (sleepMs > 0)
|
|
341
|
+
await this.sleep(sleepMs);
|
|
342
|
+
continue;
|
|
261
343
|
}
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
if (performance.now() >= deadline)
|
|
347
|
+
break;
|
|
348
|
+
if (terminalStatuses.includes(session.status)) {
|
|
349
|
+
throw new SessionError(`Session entered ${session.status} state during provisioning`, 'Try creating a new session with: thinkrun cloud start');
|
|
350
|
+
}
|
|
351
|
+
if (readyStatuses.includes(session.status) && session.browserReady === true) {
|
|
262
352
|
return session;
|
|
263
353
|
}
|
|
264
|
-
|
|
354
|
+
const sleepMs = Math.min(pollInterval, Math.max(0, deadline - performance.now()));
|
|
355
|
+
if (sleepMs > 0)
|
|
356
|
+
await this.sleep(sleepMs);
|
|
265
357
|
}
|
|
266
358
|
throw new SessionError('Session provisioning timed out', 'The session may still be starting. Check with: thinkrun cloud status');
|
|
267
359
|
}
|
|
@@ -275,7 +367,10 @@ export class CloudAdapter {
|
|
|
275
367
|
}
|
|
276
368
|
}
|
|
277
369
|
async getSession(sessionId) {
|
|
278
|
-
|
|
370
|
+
return this.readSession(sessionId);
|
|
371
|
+
}
|
|
372
|
+
async readSession(sessionId, timeoutMs, retries = 3) {
|
|
373
|
+
const response = await this.request(`/api/sessions/${sessionId}`, timeoutMs === undefined ? {} : { timeoutMs }, retries);
|
|
279
374
|
if (response?.data)
|
|
280
375
|
return response.data;
|
|
281
376
|
return response;
|