@atolis-hq/wake 0.3.115 → 0.3.116

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.
@@ -108,4 +108,4 @@ export function resolveWakeVersion(options = {}) {
108
108
  return `g${headHash.slice(0, 7)}`;
109
109
  return '0.1.0-dev';
110
110
  }
111
- export const wakeVersion = "g67783ec";
111
+ export const wakeVersion = "g7af14f8";
@@ -1,266 +1,55 @@
1
- import { readFile, readdir } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { readFile } from 'node:fs/promises';
3
2
  import { pathToFileURL } from 'node:url';
4
- import { isTerminalWaitOutput, structuredResult, writeStdinSessionArgument, } from './codex-stop-hook-protocol.js';
5
- export const unverifiedCodexCompletionReason = 'unverified: could not confirm background command completion from Codex structured telemetry';
3
+ export const waitBackgroundStatus = 'WAIT_BACKGROUND';
6
4
  /**
7
- * Bound on how long this hook will keep forcing continuation for the same
8
- * unresolved cell within one process segment before giving up and letting
9
- * the turn end anyway. A retry *count* doesn't track this reliably — cycle
10
- * length varies enormously with how long the model's own `wait` calls choose
11
- * to yield for (observed from ~1s to 50s+ per call in production), so a
12
- * fixed count either gives up far too early on a real multi-minute command
13
- * or far too late on a broken loop that isn't waiting on anything real.
14
- *
15
- * Real observed `npm run verify`/`verify:ci` durations range from ~90s to
16
- * over 20 minutes, so this value is a deliberate tradeoff rather than a safe
17
- * upper bound on every legitimate case: a genuinely long-running command that
18
- * outlasts it will have its live retry loop give up before finishing, and
19
- * fall through to a `BLOCKED` outcome needing a human `/retry` instead of
20
- * confirming cleanly on its own. That's an accepted cost, not a correctness
21
- * gap — giving up here never weakens the guarantee, since the post-run
22
- * fallback (`verifyCodexSession`) independently re-scans the same transcript
23
- * after the process exits and still reports the run as unverified if the
24
- * cell is genuinely still unresolved. This limit exists only to bound
25
- * wasted time/tokens against a detection gap we haven't found yet, not to
26
- * replace correct detection.
27
- */
28
- export const maxLiveHookRetryMs = 10 * 60 * 1000;
29
- /**
30
- * Inspect only Codex's structured function-call protocol. Command output is
31
- * opaque except for the protocol's managed-cell and terminal-result envelopes.
32
- *
33
- * Exec/wait cells live in one `codex exec` process's memory and never survive
34
- * a resume into a new process, so only the segment of the transcript since
35
- * the current process attached (its `session_meta`/`turn_context` marker)
36
- * can hold a cell that might still be genuinely pending. A cell referenced
37
- * only in an earlier segment belongs to a process that has already exited
38
- * and can never return an exit code again — scoping to the latest segment
39
- * is what makes that structurally certain, rather than trying to recognise
40
- * every shape of "this cell is gone" text a stale reference might produce.
5
+ * WAIT_BACKGROUND is a Codex-only, intermediate final response. It is not a
6
+ * Wake outcome: the hook rejects it and gives Codex another turn to obtain a
7
+ * terminal result before it reports DONE, BLOCKED, NEEDS_CLARIFICATION, or
8
+ * FAILED.
41
9
  */
42
10
  export function inspectCodexTranscript(transcript) {
43
- const lines = transcript.split(/\r?\n/).filter((line) => line.trim().length > 0);
44
- const boundary = lastProcessBoundary(lines);
45
- const telemetry = {
46
- calls: new Map(),
47
- pendingCells: new Set(),
48
- resolvedCells: new Set(),
49
- unresolvableCells: new Set(),
50
- sessionsByCell: new Map(),
51
- };
52
- for (const line of lines.slice(boundary + 1)) {
53
- const event = parseJson(line);
54
- if (event === undefined)
55
- return blocked('could not parse Codex structured telemetry');
56
- const payload = record(event.payload);
57
- if (payload !== undefined)
58
- consumePayload(payload, telemetry);
59
- }
60
- const unresolved = [...telemetry.pendingCells].filter((cellId) => !telemetry.resolvedCells.has(cellId));
61
- if (unresolved.length === 0)
62
- return {};
63
- // A cell whose own `wait` call has already reported it gone (a distinct,
64
- // cell-identity-specific protocol error, not a general failure) can never
65
- // return an exit code no matter how many more times it's polled. Asking
66
- // the model to keep retrying it is not just wasted effort, it's actively
67
- // wrong instructions — so stop retrying that specific cell immediately
68
- // rather than waiting out the general time backstop. The cell still
69
- // counts as unresolved for the block decision itself: it genuinely never
70
- // confirmed completion, it just isn't worth telling the model to poll
71
- // again.
72
- const retryable = unresolved.filter((cellId) => !telemetry.unresolvableCells.has(cellId));
73
- if (retryable.length === 0)
74
- return {};
75
- if (liveHookRetryElapsedMs(lines.slice(boundary + 1)) >= maxLiveHookRetryMs)
76
- return {};
77
- return blocked(`Codex cell ${retryable[0]} has no terminal exit_code; continue polling that cell`);
78
- }
79
- /**
80
- * Elapsed wall-clock time since this hook's own first continuation prompt
81
- * within the current process segment, using the transcript's own event
82
- * timestamps rather than a call/retry count. Returns 0 (never give up) when
83
- * there is no prior retry yet, or when a timestamp can't be established —
84
- * giving up is the direction that stops enforcing, so any doubt should keep
85
- * blocking rather than silently switch to time-based give-up on weak evidence.
86
- */
87
- function liveHookRetryElapsedMs(segment) {
88
- let firstRetryAt;
89
- let latestAt;
90
- for (const line of segment) {
91
- const event = parseJson(line);
92
- if (event === undefined)
93
- continue;
94
- const at = timestampMs(event.timestamp);
95
- if (at !== undefined)
96
- latestAt = at;
97
- const payload = record(event.payload);
98
- if (payload?.type !== 'message' || payload.role !== 'user')
99
- continue;
100
- if (firstRetryAt === undefined &&
101
- at !== undefined &&
102
- userMessageText(payload.content).includes('<hook_prompt'))
103
- firstRetryAt = at;
104
- }
105
- return firstRetryAt === undefined || latestAt === undefined ? 0 : latestAt - firstRetryAt;
106
- }
107
- function timestampMs(value) {
108
- if (typeof value !== 'string')
109
- return undefined;
110
- const parsed = Date.parse(value);
111
- return Number.isFinite(parsed) ? parsed : undefined;
112
- }
113
- function userMessageText(content) {
114
- if (!Array.isArray(content))
115
- return '';
116
- return content
117
- .map((item) => {
118
- const entry = record(item);
119
- return entry === undefined ? '' : (string(entry.text) ?? '');
120
- })
121
- .join('');
122
- }
123
- function lastProcessBoundary(lines) {
124
- let boundary = -1;
125
- lines.forEach((line, index) => {
126
- const event = parseJson(line);
127
- if (event?.type === 'session_meta' || event?.type === 'turn_context')
128
- boundary = index;
129
- });
130
- return boundary;
131
- }
132
- function consumePayload(payload, telemetry) {
133
- if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
134
- recordToolCall(payload, telemetry.calls);
135
- return;
136
- }
137
- if (payload.type === 'custom_tool_call_output' || payload.type === 'function_call_output')
138
- recordToolOutput(payload, telemetry);
139
- }
140
- function recordToolCall(payload, calls) {
141
- const callId = string(payload.call_id);
142
- const name = toolName(payload.name);
143
- if (callId === undefined || name === undefined)
144
- return;
145
- calls.set(callId, {
146
- name,
147
- ...(name === 'wait' ? cellArgument(payload.arguments ?? payload.input) : {}),
148
- ...(name === 'exec' ? { spawnsBackgroundJob: spawnsBackgroundJob(payload.input) } : {}),
149
- ...(name === 'exec' ? writeStdinSessionArgument(payload.input) : {}),
150
- });
151
- }
152
- /**
153
- * The `exec` tool is a shared JS sandbox: `tools.exec_command(...)` spawns a
154
- * genuine one-shot background job whose cell should eventually resolve to a
155
- * real exit code. `tools.write_stdin(...)` instead interacts with an
156
- * already-existing, intentionally long-lived session (e.g. a dev server kept
157
- * running for e2e checks) — that cell is never meant to terminate, so
158
- * flagging it as an unresolved background command would be a false positive.
159
- * Default to treating a call as job-spawning whenever it can't be positively
160
- * identified as pure session interaction, matching the fail-closed posture
161
- * used everywhere else in this file.
162
- */
163
- function spawnsBackgroundJob(input) {
164
- if (typeof input !== 'string')
165
- return true;
166
- const interactsWithSession = /tools\.write_stdin\s*\(/.test(input);
167
- const spawnsJob = /tools\.exec_command\s*\(/.test(input);
168
- return spawnsJob || !interactsWithSession;
169
- }
170
- function recordToolOutput(payload, telemetry) {
171
- const callId = string(payload.call_id);
172
- const call = callId === undefined ? undefined : telemetry.calls.get(callId);
173
- if (call === undefined)
174
- return;
175
- const result = structuredResult(payload.output);
176
- if (call.name === 'exec')
177
- return recordExecOutput(call, result, telemetry);
178
- recordWaitOutput(call, result, payload.output, telemetry);
179
- }
180
- function recordExecOutput(call, result, telemetry) {
181
- if (call.spawnsBackgroundJob === true && result.exitCode === undefined && result.pendingCellId)
182
- telemetry.pendingCells.add(result.pendingCellId);
183
- if (call.writeStdinSessionId !== undefined && result.pendingCellId !== undefined)
184
- telemetry.sessionsByCell.set(result.pendingCellId, call.writeStdinSessionId);
185
- if (call.writeStdinSessionId === undefined || result.jsonExitCode === undefined)
186
- return;
187
- resolveSession(call.writeStdinSessionId, telemetry);
188
- }
189
- function resolveSession(sessionId, telemetry) {
190
- for (const [cellId, recordedSessionId] of telemetry.sessionsByCell) {
191
- if (recordedSessionId === sessionId)
192
- telemetry.resolvedCells.add(cellId);
193
- }
194
- }
195
- function recordWaitOutput(call, result, output, telemetry) {
196
- if (call.cellId === undefined)
197
- return;
198
- const nativeTerminal = result.sessionId === undefined && isTerminalWaitOutput(output);
199
- const terminal = result.exitCode !== undefined || nativeTerminal;
200
- if (terminal) {
201
- telemetry.resolvedCells.add(call.cellId);
202
- const sessionId = telemetry.sessionsByCell.get(call.cellId);
203
- if (sessionId !== undefined && (result.jsonExitCode !== undefined || nativeTerminal))
204
- resolveSession(sessionId, telemetry);
205
- }
206
- if (result.sessionId !== undefined)
207
- telemetry.sessionsByCell.set(call.cellId, result.sessionId);
208
- if (result.notFoundCellId === call.cellId)
209
- telemetry.unresolvableCells.add(call.cellId);
11
+ return lastAssistantMessage(transcript) === waitBackgroundStatus
12
+ ? {
13
+ decision: 'block',
14
+ reason: 'Codex reported WAIT_BACKGROUND. Do not end this turn. Poll every command still running from this turn and report a normal terminal status only after each has settled.',
15
+ }
16
+ : {};
210
17
  }
211
18
  export async function runCodexStopHook(input) {
212
19
  const payload = record(input);
213
20
  const transcriptPath = payload === undefined ? undefined : string(payload.transcript_path);
214
21
  if (transcriptPath === undefined)
215
- return blocked('Stop hook received no transcript_path');
22
+ return {};
216
23
  try {
217
24
  return inspectCodexTranscript(await readFile(transcriptPath, 'utf8'));
218
25
  }
219
26
  catch {
220
- return blocked('could not read Codex transcript');
27
+ return {};
221
28
  }
222
29
  }
223
- export async function verifyCodexSession(codexHome, sessionId) {
224
- if (codexHome === undefined || sessionId === undefined)
225
- return postRunBlocked('could not locate Codex structured telemetry');
226
- const transcriptPath = await transcriptForSession(join(codexHome, 'sessions'), sessionId);
227
- if (transcriptPath === undefined)
228
- return postRunBlocked('could not locate Codex structured telemetry');
229
- return postRunDecision(await runCodexStopHook({ transcript_path: transcriptPath }));
230
- }
231
- async function transcriptForSession(directory, sessionId) {
232
- try {
233
- for (const entry of await readdir(directory, { withFileTypes: true })) {
234
- const path = join(directory, entry.name);
235
- if (entry.isDirectory()) {
236
- const nested = await transcriptForSession(path, sessionId);
237
- if (nested !== undefined)
238
- return nested;
239
- }
240
- else if (entry.isFile() && entry.name.endsWith(`-${sessionId}.jsonl`))
241
- return path;
242
- }
243
- }
244
- catch {
245
- return undefined;
30
+ function lastAssistantMessage(transcript) {
31
+ const lines = transcript.split(/\r?\n/);
32
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
33
+ const event = parseJson(lines[index] ?? '');
34
+ const payload = event === undefined ? undefined : record(event.payload);
35
+ if (payload?.type !== 'message' ||
36
+ payload.role !== 'assistant' ||
37
+ payload.phase !== 'final_answer')
38
+ continue;
39
+ return messageText(payload.content);
246
40
  }
247
41
  return undefined;
248
42
  }
249
- function cellArgument(value) {
250
- const arguments_ = typeof value === 'string' ? parseJson(value) : record(value);
251
- const cellId = arguments_ === undefined ? undefined : string(arguments_.cell_id);
252
- return cellId === undefined ? {} : { cellId };
253
- }
254
- function blocked(detail) {
255
- return { decision: 'block', reason: `${unverifiedCodexCompletionReason}: ${detail}` };
256
- }
257
- function postRunBlocked(detail) {
258
- return postRunDecision(blocked(detail));
259
- }
260
- function postRunDecision(decision) {
261
- return decision.decision === 'block' && decision.reason !== undefined
262
- ? { ...decision, reason: `caught by post-run verification: ${decision.reason}` }
263
- : decision;
43
+ function messageText(content) {
44
+ if (!Array.isArray(content))
45
+ return undefined;
46
+ const texts = content.map((item) => {
47
+ const entry = record(item);
48
+ if (entry?.type !== 'output_text')
49
+ return undefined;
50
+ return string(entry.text);
51
+ });
52
+ return texts.every((text) => text !== undefined) ? texts.join('') : undefined;
264
53
  }
265
54
  function parseJson(value) {
266
55
  try {
@@ -270,9 +59,6 @@ function parseJson(value) {
270
59
  return undefined;
271
60
  }
272
61
  }
273
- function toolName(value) {
274
- return value === 'exec' || value === 'wait' ? value : undefined;
275
- }
276
62
  function record(value) {
277
63
  return typeof value === 'object' && value !== null && !Array.isArray(value)
278
64
  ? value
@@ -1,6 +1,5 @@
1
1
  import { ProviderQuotaExceededFailureKind } from '../../contracts/runner.js';
2
- import { RunStatus, WorkspaceMode } from '../../contracts/vocabulary.js';
3
- import { verifyCodexSession } from '../codex-stop-hook.js';
2
+ import { WorkspaceMode } from '../../contracts/vocabulary.js';
4
3
  import { cliRunner } from './claude.js';
5
4
  // Deliberately narrow: only genuine provider usage/rate-limit phrasing.
6
5
  // Auth/login failures (unauthorized, authentication, api key, not logged
@@ -45,23 +44,7 @@ export function createCodexRunner(options = {}) {
45
44
  classifyFailure: classifyCodexFailure,
46
45
  supportsSessionResume: true,
47
46
  });
48
- return {
49
- supportsSessionResume: true,
50
- async start(request, signal) {
51
- const execution = await runner.start(request, signal);
52
- return {
53
- ...execution,
54
- result: execution.result.then(async (result) => {
55
- if (result.transport !== RunStatus.Succeeded)
56
- return result;
57
- const decision = await verifyCodexSession(options.codexHome ?? process.env.CODEX_HOME, result.sessionId);
58
- return decision.decision === undefined
59
- ? result
60
- : { ...result, unverifiedCompletionReason: decision.reason };
61
- }),
62
- };
63
- },
64
- };
47
+ return runner;
65
48
  }
66
49
  export function codexCommandArgs(request, passthroughArgs = [], defaults = {}) {
67
50
  const model = request.model ?? defaults.model;
@@ -79,9 +62,11 @@ export function codexCommandArgs(request, passthroughArgs = [], defaults = {}) {
79
62
  : ['-c', `model_reasoning_effort=${request.effort ?? defaults.effort}`]),
80
63
  ...(request.resumeSessionId === undefined ? [] : ['resume', request.resumeSessionId]),
81
64
  ...passthroughArgs,
82
- request.prompt,
65
+ `${request.prompt}\n\n${waitBackgroundInstruction}`,
83
66
  ];
84
67
  }
68
+ // Work around Codex's missing background-command lifecycle contract (https://github.com/openai/codex/issues/32505, https://github.com/openai/codex/issues/34866).
69
+ const waitBackgroundInstruction = `When a command you started is still running or lacks a terminal result, do not report a normal Wake outcome. Make your entire final response exactly WAIT_BACKGROUND. Wake will reject that stop attempt and ask you to continue. After that hook prompt, poll the still-running command and report a normal terminal status only after it has settled. Do not use WAIT_BACKGROUND for a human-input or implementation blocker.`;
85
70
  function codexSandboxMode(workspaceMode) {
86
71
  return workspaceMode === WorkspaceMode.Branch ? 'danger-full-access' : 'workspace-write';
87
72
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/wake",
3
- "version": "0.3.115",
3
+ "version": "0.3.116",
4
4
  "description": "Local autonomous agent control plane for software development",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -1,219 +0,0 @@
1
- export function isTerminalWaitOutput(value) {
2
- if (!Array.isArray(value) || value.length !== 2)
3
- return false;
4
- const initialOutput = record(value[0]);
5
- const finalOutput = record(value[1]);
6
- return (initialOutput?.type === 'input_text' &&
7
- typeof initialOutput.text === 'string' &&
8
- finalOutput?.type === 'input_text' &&
9
- finalOutput.text === '');
10
- }
11
- export function structuredResult(value) {
12
- return outputTexts(value).reduce(mergeResult, {});
13
- }
14
- function mergeResult(result, text) {
15
- const jsonExitCode = jsonExitCodeInText(text);
16
- const session = sessionIdInText(text);
17
- const legacyExitCode = legacyExitCodeInText(text);
18
- const exitCode = jsonExitCode ?? legacyExitCode;
19
- return {
20
- ...result,
21
- ...(jsonExitCode === undefined ? {} : { jsonExitCode }),
22
- ...(exitCode === undefined ? {} : { exitCode }),
23
- ...(session === undefined ? {} : { sessionId: session }),
24
- ...matchValue(text, /Script running with cell ID ([^\s]+)/, 'pendingCellId'),
25
- ...matchValue(text, /exec cell ([^\s]+) not found/, 'notFoundCellId'),
26
- };
27
- }
28
- function matchValue(text, pattern, key) {
29
- const value = pattern.exec(text)?.[1];
30
- return value === undefined ? {} : { [key]: value };
31
- }
32
- function jsonExitCodeInText(text) {
33
- const result = parseJson(text);
34
- return result === undefined ? undefined : number(result.exit_code);
35
- }
36
- function legacyExitCodeInText(text) {
37
- const rendered = /Exit code:\s*(-?\d+)/.exec(text)?.[1];
38
- return rendered === undefined ? undefined : Number(rendered);
39
- }
40
- function sessionIdInText(text) {
41
- const result = parseJson(text);
42
- return result === undefined ? undefined : sessionId(result.session_id);
43
- }
44
- function outputTexts(value) {
45
- if (typeof value === 'string')
46
- return [value];
47
- if (!Array.isArray(value))
48
- return [];
49
- return value.flatMap((item) => {
50
- const content = record(item);
51
- const text = content === undefined ? undefined : string(content.text);
52
- return text === undefined ? [] : [text];
53
- });
54
- }
55
- export function writeStdinSessionArgument(input) {
56
- if (typeof input !== 'string')
57
- return {};
58
- const code = codeMask(input);
59
- const calls = [...code.matchAll(/\btools\.write_stdin\s*\(\s*\{/g)];
60
- if (calls.length !== 1)
61
- return {};
62
- const call = calls[0];
63
- if (call === undefined || call.index === undefined)
64
- return {};
65
- const openObject = call.index + call[0].lastIndexOf('{');
66
- const literal = directSessionIdArgument(input, code, openObject);
67
- return literal === undefined ? {} : { writeStdinSessionId: literal };
68
- }
69
- function directSessionIdArgument(source, code, openObject) {
70
- const literals = directSessionLiterals(source, code, openObject);
71
- return literals.length === 1 ? literals[0] : undefined;
72
- }
73
- function directSessionLiterals(source, code, openObject) {
74
- const literals = [];
75
- let depth = 1;
76
- for (let index = openObject + 1; index < code.length && depth > 0; index += 1) {
77
- depth = nextDepth(code[index], depth);
78
- if (depth !== 1 || !isSessionIdAt(code, index))
79
- continue;
80
- const literal = literalAtProperty(source, code, index);
81
- if (literal === undefined)
82
- return [];
83
- literals.push(literal);
84
- }
85
- return literals;
86
- }
87
- function nextDepth(character, depth) {
88
- if (character === '{' || character === '[' || character === '(')
89
- return depth + 1;
90
- if (character === '}' || character === ']' || character === ')')
91
- return depth - 1;
92
- return depth;
93
- }
94
- function isSessionIdAt(code, index) {
95
- const name = 'session_id';
96
- return (code.startsWith(name, index) &&
97
- !/[A-Za-z0-9_$]/.test(code[index - 1] ?? '') &&
98
- !/[A-Za-z0-9_$]/.test(code[index + name.length] ?? ''));
99
- }
100
- function literalAtProperty(source, code, index) {
101
- let valueStart = index + 'session_id'.length;
102
- while (/\s/.test(code[valueStart] ?? ''))
103
- valueStart += 1;
104
- return code[valueStart] === ':' ? sourceSessionLiteralAt(source, valueStart + 1) : undefined;
105
- }
106
- function codeMask(source) {
107
- const characters = source.split('');
108
- for (let index = 0; index < characters.length; index += 1)
109
- index = maskAt(characters, index);
110
- return characters.join('');
111
- }
112
- function maskAt(characters, index) {
113
- const character = characters[index];
114
- if (character === '/' && characters[index + 1] === '/')
115
- return maskLineComment(characters, index);
116
- if (character === '/' && characters[index + 1] === '*')
117
- return maskBlockComment(characters, index);
118
- return isQuote(character) ? maskQuoted(characters, index, character) : index;
119
- }
120
- function maskLineComment(characters, index) {
121
- while (index < characters.length && characters[index] !== '\n')
122
- characters[index++] = ' ';
123
- return index;
124
- }
125
- function maskBlockComment(characters, index) {
126
- characters[index++] = ' ';
127
- characters[index++] = ' ';
128
- while (index < characters.length && !(characters[index] === '*' && characters[index + 1] === '/'))
129
- characters[index++] = ' ';
130
- characters[index++] = ' ';
131
- characters[index] = ' ';
132
- return index;
133
- }
134
- function isQuote(value) {
135
- return value === '"' || value === "'" || value === '`';
136
- }
137
- function maskQuoted(characters, index, quote) {
138
- characters[index++] = ' ';
139
- while (index < characters.length) {
140
- const current = characters[index];
141
- characters[index++] = ' ';
142
- if (current === '\\') {
143
- characters[index++] = ' ';
144
- continue;
145
- }
146
- if (current === quote)
147
- break;
148
- }
149
- return index;
150
- }
151
- function sourceSessionLiteralAt(source, start) {
152
- while (/\s/.test(source[start] ?? ''))
153
- start += 1;
154
- const numeric = sourceNumberLiteralAt(source, start);
155
- if (numeric !== undefined)
156
- return sessionId(numeric);
157
- if (source[start] === "'")
158
- return sessionId(singleQuotedStringAt(source, start));
159
- if (source[start] !== '"')
160
- return undefined;
161
- const quoted = doubleQuotedStringAt(source, start);
162
- return quoted === undefined ? undefined : sessionId(quoted);
163
- }
164
- function doubleQuotedStringAt(source, start) {
165
- let end = start + 1;
166
- while (end < source.length) {
167
- if (source[end] === '\\') {
168
- end += 2;
169
- continue;
170
- }
171
- if (source[end] === '"') {
172
- const value = parseJson(`{"value":${source.slice(start, end + 1)}}`);
173
- return value === undefined ? undefined : string(value.value);
174
- }
175
- end += 1;
176
- }
177
- return undefined;
178
- }
179
- function sourceNumberLiteralAt(source, start) {
180
- const match = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
181
- match.lastIndex = start;
182
- const literal = match.exec(source)?.[0];
183
- if (literal === undefined || /[A-Za-z0-9_$.]/.test(source[start + literal.length] ?? ''))
184
- return undefined;
185
- const value = Number(literal);
186
- return Number.isFinite(value) ? value : undefined;
187
- }
188
- function singleQuotedStringAt(source, start) {
189
- let end = start + 1;
190
- while (end < source.length && source[end] !== "'") {
191
- if (source[end] === '\\')
192
- return undefined;
193
- end += 1;
194
- }
195
- return end < source.length ? source.slice(start + 1, end) : undefined;
196
- }
197
- function parseJson(value) {
198
- try {
199
- return record(JSON.parse(value));
200
- }
201
- catch {
202
- return undefined;
203
- }
204
- }
205
- function record(value) {
206
- return typeof value === 'object' && value !== null && !Array.isArray(value)
207
- ? value
208
- : undefined;
209
- }
210
- function string(value) {
211
- return typeof value === 'string' ? value : undefined;
212
- }
213
- function number(value) {
214
- return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
215
- }
216
- function sessionId(value) {
217
- const text = string(value);
218
- return text === undefined || text.length === 0 ? number(value) : text;
219
- }