eve 0.27.6 → 0.27.8
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/CHANGELOG.md +14 -0
- package/dist/src/channel/session.d.ts +5 -0
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +7 -0
- package/dist/src/chunks/{use-eve-agent-COlXhAaF.js → use-eve-agent-JPfBHZJr.js} +36 -6
- package/dist/src/chunks/{use-eve-agent-DzVlKcUV.js → use-eve-agent-r5tkzjmt.js} +36 -6
- package/dist/src/cli/commands/register-registry-commands.d.ts +12 -0
- package/dist/src/cli/commands/register-registry-commands.js +1 -0
- package/dist/src/cli/commands/registry-project.d.ts +10 -0
- package/dist/src/cli/commands/registry-project.js +1 -0
- package/dist/src/cli/commands/registry.d.ts +17 -0
- package/dist/src/cli/commands/registry.js +1 -0
- package/dist/src/cli/run.js +2 -2
- package/dist/src/client/open-stream.d.ts +17 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +5 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +7 -0
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/shadcn-registry/LICENSE.md +21 -0
- package/dist/src/compiled/shadcn-registry/index.d.ts +56 -0
- package/dist/src/compiled/shadcn-registry/index.js +33491 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/runtime-actions.d.ts +4 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/tool-call-input-errors.d.ts +20 -0
- package/dist/src/harness/tool-call-input-errors.js +1 -1
- package/dist/src/internal/application/build-workspace.d.ts +0 -1
- package/dist/src/internal/application/build-workspace.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/application/paths.d.ts +1 -6
- package/dist/src/internal/application/paths.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.d.ts +4 -4
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
- package/dist/src/internal/nitro/host/create-application-nitro.d.ts +11 -7
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/types.d.ts +0 -4
- package/dist/src/internal/nitro/host/vercel-build-output-config.d.ts +29 -1
- package/dist/src/internal/nitro/host/vercel-build-output-config.js +1 -1
- package/dist/src/internal/workflow/queue-namespace.d.ts +8 -0
- package/dist/src/internal/workflow/queue-namespace.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.d.ts +0 -5
- package/dist/src/internal/workflow-bundle/builder.d.ts +0 -5
- package/dist/src/internal/workflow-bundle/builder.js +2 -2
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.d.ts +0 -51
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -3
- package/dist/src/internal/workflow-bundle/workflow-builders.d.ts +0 -7
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/message.d.ts +1 -0
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/eve.js +2 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +21 -20
- package/docs/channels/custom.mdx +1 -1
- package/docs/channels/overview.mdx +2 -0
- package/docs/channels/slack.mdx +0 -1
- package/docs/concepts/{execution-model-and-durability.md → execution-model-and-durability.mdx} +16 -0
- package/docs/concepts/security-model.md +2 -0
- package/docs/concepts/sessions-runs-and-streaming.md +9 -0
- package/docs/getting-started.mdx +13 -196
- package/docs/guides/client/streaming.mdx +15 -0
- package/docs/install-integrations.mdx +106 -0
- package/docs/installation.mdx +60 -0
- package/docs/meta.json +8 -6
- package/docs/project-structure.mdx +53 -0
- package/docs/reference/cli.md +18 -0
- package/docs/tutorial/meta.json +1 -1
- package/package.json +2 -1
- package/docs/introduction.mdx +0 -103
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.27.8
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- a69faae: Add `eve add` and `eve registry` commands for installing and discovering official or configured shadcn registry items.
|
|
8
|
+
|
|
9
|
+
## 0.27.7
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 3c53306: Vercel builds now run a single Nitro build. The workflow flow function is emitted through Nitro's per-route `functionRules` (queue trigger, `maxDuration: "max"`, precondition guard) instead of a second standalone Nitro build that was copied and retargeted into the output, making `eve build` on Vercel roughly twice as fast.
|
|
14
|
+
- e368fcd: The client's `session.stream()` accepts `follow: false` for bounded catch-up reads (`follow` defaults to `true`, following the live stream): it consumes events from the cursor to the durable tail observed when the stream opens — surviving reconnects and still advancing the stored `streamIndex` — then returns instead of following the live stream. The HTTP stream route reports the durable tail as the `x-eve-stream-tail-index` response header when a request opts in with `includeTailIndex=1`, and channel-authoring `Session` objects gain `getStreamTailIndex()` for serving bounded reads from custom routes.
|
|
15
|
+
- 7e4f7ef: Tool calls whose arguments arrive as a raw JSON string (e.g. provider-executed server tools) are now parsed, and arguments that cannot be parsed at all — such as malformed JSON emitted by the model — surface as a failed tool result the model can react to instead of failing the whole turn.
|
|
16
|
+
|
|
3
17
|
## 0.27.6
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
|
@@ -30,6 +30,11 @@ export interface Session {
|
|
|
30
30
|
getEventStream(options?: {
|
|
31
31
|
startIndex?: number;
|
|
32
32
|
}): Promise<ReadableStream<HandleMessageStreamEvent>>;
|
|
33
|
+
/**
|
|
34
|
+
* Resolves the durable tail of the event stream: the zero-based index of
|
|
35
|
+
* the last recorded event, or `-1` before the first.
|
|
36
|
+
*/
|
|
37
|
+
getStreamTailIndex(): Promise<number>;
|
|
33
38
|
}
|
|
34
39
|
/**
|
|
35
40
|
* Live handle to the current session, exposed on `ctx.session` to
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AuthKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";function createSession(e,t,n){return{id:e,continuationToken:t,async cancel(t){return n.cancelTurn({sessionId:e,turnId:t?.turnId})},async getEventStream(t){return n.getEventStream(e,t)}}}function createGetSessionFn(e){return t=>createSession(t,``,e)}function buildSessionHandle(i){return{get id(){return i.get(SessionIdKey)??``},get continuationToken(){return i.get(ContinuationTokenKey)??``},get auth(){return{current:i.get(AuthKey)??null,initiator:i.get(InitiatorAuthKey)??null}},setContinuationToken(e){let n=i.get(ContinuationTokenKey)??``,r=namespaceContinuationToken(n,e);n!==r&&i.set(ContinuationTokenKey,r)}}}function namespaceContinuationToken(e,t){let n=e.indexOf(`:`);if(n<=0)throw Error(`Cannot set session continuation token without an existing namespaced continuation token. Start the session with a placeholder continuationToken.`);return`${e.slice(0,n+1)}${t}`}export{buildSessionHandle,createGetSessionFn,createSession};
|
|
1
|
+
import{AuthKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";function createSession(e,t,n){return{id:e,continuationToken:t,async cancel(t){return n.cancelTurn({sessionId:e,turnId:t?.turnId})},async getEventStream(t){return n.getEventStream(e,t)},async getStreamTailIndex(){return n.getStreamTailIndex(e)}}}function createGetSessionFn(e){return t=>createSession(t,``,e)}function buildSessionHandle(i){return{get id(){return i.get(SessionIdKey)??``},get continuationToken(){return i.get(ContinuationTokenKey)??``},get auth(){return{current:i.get(AuthKey)??null,initiator:i.get(InitiatorAuthKey)??null}},setContinuationToken(e){let n=i.get(ContinuationTokenKey)??``,r=namespaceContinuationToken(n,e);n!==r&&i.set(ContinuationTokenKey,r)}}}function namespaceContinuationToken(e,t){let n=e.indexOf(`:`);if(n<=0)throw Error(`Cannot set session continuation token without an existing namespaced continuation token. Start the session with a placeholder continuationToken.`);return`${e.slice(0,n+1)}${t}`}export{buildSessionHandle,createGetSessionFn,createSession};
|
|
@@ -368,6 +368,13 @@ export interface Runtime {
|
|
|
368
368
|
* parameter unchanged.
|
|
369
369
|
*/
|
|
370
370
|
getEventStream(sessionId: string, options?: GetEventStreamOptions): Promise<ReadableStream<HandleMessageStreamEvent>>;
|
|
371
|
+
/**
|
|
372
|
+
* Resolves the durable tail of a session's event stream: the zero-based
|
|
373
|
+
* index of the last recorded event, or `-1` before the first. Callers use
|
|
374
|
+
* it to bound a read at the tail they observed instead of following the
|
|
375
|
+
* live stream.
|
|
376
|
+
*/
|
|
377
|
+
getStreamTailIndex(sessionId: string): Promise<number>;
|
|
371
378
|
}
|
|
372
379
|
/**
|
|
373
380
|
* Options accepted by {@link Runtime.getEventStream}.
|
|
@@ -299,6 +299,7 @@ function safeJsonStringify(value) {
|
|
|
299
299
|
//#endregion
|
|
300
300
|
//#region src/protocol/message.ts
|
|
301
301
|
const EVE_SESSION_ID_HEADER = "x-eve-session-id";
|
|
302
|
+
const EVE_STREAM_TAIL_INDEX_HEADER = "x-eve-stream-tail-index";
|
|
302
303
|
const textEncoder = new TextEncoder();
|
|
303
304
|
function isCurrentTurnBoundaryEvent(event) {
|
|
304
305
|
return event.type === "session.completed" || event.type === "session.failed" || event.type === "session.waiting";
|
|
@@ -531,32 +532,47 @@ function resolveStreamReconnectPolicy(policy) {
|
|
|
531
532
|
};
|
|
532
533
|
}
|
|
533
534
|
async function* followStreamIterable(input) {
|
|
535
|
+
if (input.follow === false && input.startIndex < 0) throw new Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");
|
|
534
536
|
const retryPolicy = resolveStreamReconnectPolicy(input.streamReconnectPolicy);
|
|
535
537
|
const idleRetryPolicy = retryPolicy.streamIdleReconnectPolicy;
|
|
536
538
|
let startIndex = input.startIndex;
|
|
537
539
|
let reconnectDelayMs = idleRetryPolicy.baseDelayMs;
|
|
538
540
|
let idleReconnects = 0;
|
|
539
541
|
let initialConnection = true;
|
|
542
|
+
let tailIndex;
|
|
540
543
|
while (true) {
|
|
541
|
-
let
|
|
544
|
+
let connection;
|
|
542
545
|
try {
|
|
543
|
-
|
|
546
|
+
connection = await openStreamBody({
|
|
544
547
|
...input,
|
|
545
548
|
retryPolicy,
|
|
546
|
-
startIndex
|
|
549
|
+
startIndex,
|
|
550
|
+
requestTailIndex: input.follow === false && tailIndex === void 0
|
|
547
551
|
});
|
|
548
552
|
} catch (error) {
|
|
549
553
|
if (input.signal?.aborted) return;
|
|
550
554
|
throw error;
|
|
551
555
|
}
|
|
556
|
+
if (input.follow === false && tailIndex === void 0) {
|
|
557
|
+
tailIndex = connection.tailIndex;
|
|
558
|
+
if (tailIndex === void 0) {
|
|
559
|
+
await connection.body.cancel().catch(() => {});
|
|
560
|
+
throw new Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (tailIndex !== void 0 && startIndex > tailIndex) {
|
|
564
|
+
await connection.body.cancel().catch(() => {});
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
552
567
|
let deliveredEvent = false;
|
|
553
568
|
try {
|
|
554
|
-
for await (const event of readNdjsonStream(body)) {
|
|
569
|
+
for await (const event of readNdjsonStream(connection.body)) {
|
|
555
570
|
startIndex += 1;
|
|
556
571
|
deliveredEvent = true;
|
|
557
572
|
reconnectDelayMs = idleRetryPolicy.baseDelayMs;
|
|
558
573
|
idleReconnects = 0;
|
|
559
574
|
yield event;
|
|
575
|
+
if (tailIndex !== void 0 && startIndex > tailIndex) return;
|
|
560
576
|
}
|
|
561
577
|
} catch (error) {
|
|
562
578
|
if (!isStreamDisconnectError(error)) throw error;
|
|
@@ -576,8 +592,11 @@ async function openStreamBody(input) {
|
|
|
576
592
|
let lastBody;
|
|
577
593
|
let lastHeaders;
|
|
578
594
|
let retryDelayMs = openRetryPolicy.baseDelayMs;
|
|
595
|
+
const searchParams = {};
|
|
596
|
+
if (input.startIndex !== 0) searchParams.startIndex = String(input.startIndex);
|
|
597
|
+
if (input.requestTailIndex === true) searchParams.includeTailIndex = "1";
|
|
579
598
|
for (let attempt = 0; attempt < openRetryPolicy.maxAttempts; attempt += 1) {
|
|
580
|
-
const url = createClientUrl(input.host, createEveMessageStreamRoutePath(input.sessionId),
|
|
599
|
+
const url = createClientUrl(input.host, createEveMessageStreamRoutePath(input.sessionId), Object.keys(searchParams).length > 0 ? searchParams : void 0);
|
|
581
600
|
const headers = await input.resolveHeaders();
|
|
582
601
|
let response;
|
|
583
602
|
try {
|
|
@@ -594,7 +613,10 @@ async function openStreamBody(input) {
|
|
|
594
613
|
}
|
|
595
614
|
if (response.ok) {
|
|
596
615
|
if (!response.body) throw new ClientError(response.status, "Response body is null.", response.headers);
|
|
597
|
-
return
|
|
616
|
+
return {
|
|
617
|
+
body: response.body,
|
|
618
|
+
tailIndex: parseTailIndexHeader(response.headers)
|
|
619
|
+
};
|
|
598
620
|
}
|
|
599
621
|
lastStatus = response.status;
|
|
600
622
|
lastBody = await response.text();
|
|
@@ -607,6 +629,12 @@ async function openStreamBody(input) {
|
|
|
607
629
|
}
|
|
608
630
|
throw new ClientError(lastStatus ?? 0, lastBody ?? "Failed to open message stream.", lastHeaders);
|
|
609
631
|
}
|
|
632
|
+
function parseTailIndexHeader(headers) {
|
|
633
|
+
const raw = headers.get(EVE_STREAM_TAIL_INDEX_HEADER);
|
|
634
|
+
if (raw === null || !/^-?\d+$/.test(raw)) return;
|
|
635
|
+
const parsed = Number(raw);
|
|
636
|
+
return Number.isSafeInteger(parsed) ? parsed : void 0;
|
|
637
|
+
}
|
|
610
638
|
async function sleep$1(ms, signal) {
|
|
611
639
|
if (signal?.aborted) return;
|
|
612
640
|
await new Promise((resolve) => {
|
|
@@ -784,6 +812,7 @@ var ClientSession = class {
|
|
|
784
812
|
stream(options) {
|
|
785
813
|
const sessionId = this.#state.sessionId;
|
|
786
814
|
if (!sessionId) throw new Error("Session has no session ID. Send a message first.");
|
|
815
|
+
if (options?.follow === false && (options.startIndex ?? this.#state.streamIndex) < 0) throw new Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");
|
|
787
816
|
return this.#streamAndAdvance(sessionId, options);
|
|
788
817
|
}
|
|
789
818
|
async #postTurn(input, session) {
|
|
@@ -845,6 +874,7 @@ var ClientSession = class {
|
|
|
845
874
|
const events = [];
|
|
846
875
|
try {
|
|
847
876
|
for await (const event of followStreamIterable({
|
|
877
|
+
follow: options?.follow,
|
|
848
878
|
host: this.#context.host,
|
|
849
879
|
resolveHeaders: () => this.#context.resolveHeaders(),
|
|
850
880
|
redirect: this.#context.redirect,
|
|
@@ -299,6 +299,7 @@ function safeJsonStringify(value) {
|
|
|
299
299
|
//#endregion
|
|
300
300
|
//#region src/protocol/message.ts
|
|
301
301
|
const EVE_SESSION_ID_HEADER = "x-eve-session-id";
|
|
302
|
+
const EVE_STREAM_TAIL_INDEX_HEADER = "x-eve-stream-tail-index";
|
|
302
303
|
const textEncoder = new TextEncoder();
|
|
303
304
|
function isCurrentTurnBoundaryEvent(event) {
|
|
304
305
|
return event.type === "session.completed" || event.type === "session.failed" || event.type === "session.waiting";
|
|
@@ -531,32 +532,47 @@ function resolveStreamReconnectPolicy(policy) {
|
|
|
531
532
|
};
|
|
532
533
|
}
|
|
533
534
|
async function* followStreamIterable(input) {
|
|
535
|
+
if (input.follow === false && input.startIndex < 0) throw new Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");
|
|
534
536
|
const retryPolicy = resolveStreamReconnectPolicy(input.streamReconnectPolicy);
|
|
535
537
|
const idleRetryPolicy = retryPolicy.streamIdleReconnectPolicy;
|
|
536
538
|
let startIndex = input.startIndex;
|
|
537
539
|
let reconnectDelayMs = idleRetryPolicy.baseDelayMs;
|
|
538
540
|
let idleReconnects = 0;
|
|
539
541
|
let initialConnection = true;
|
|
542
|
+
let tailIndex;
|
|
540
543
|
while (true) {
|
|
541
|
-
let
|
|
544
|
+
let connection;
|
|
542
545
|
try {
|
|
543
|
-
|
|
546
|
+
connection = await openStreamBody({
|
|
544
547
|
...input,
|
|
545
548
|
retryPolicy,
|
|
546
|
-
startIndex
|
|
549
|
+
startIndex,
|
|
550
|
+
requestTailIndex: input.follow === false && tailIndex === void 0
|
|
547
551
|
});
|
|
548
552
|
} catch (error) {
|
|
549
553
|
if (input.signal?.aborted) return;
|
|
550
554
|
throw error;
|
|
551
555
|
}
|
|
556
|
+
if (input.follow === false && tailIndex === void 0) {
|
|
557
|
+
tailIndex = connection.tailIndex;
|
|
558
|
+
if (tailIndex === void 0) {
|
|
559
|
+
await connection.body.cancel().catch(() => {});
|
|
560
|
+
throw new Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (tailIndex !== void 0 && startIndex > tailIndex) {
|
|
564
|
+
await connection.body.cancel().catch(() => {});
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
552
567
|
let deliveredEvent = false;
|
|
553
568
|
try {
|
|
554
|
-
for await (const event of readNdjsonStream(body)) {
|
|
569
|
+
for await (const event of readNdjsonStream(connection.body)) {
|
|
555
570
|
startIndex += 1;
|
|
556
571
|
deliveredEvent = true;
|
|
557
572
|
reconnectDelayMs = idleRetryPolicy.baseDelayMs;
|
|
558
573
|
idleReconnects = 0;
|
|
559
574
|
yield event;
|
|
575
|
+
if (tailIndex !== void 0 && startIndex > tailIndex) return;
|
|
560
576
|
}
|
|
561
577
|
} catch (error) {
|
|
562
578
|
if (!isStreamDisconnectError(error)) throw error;
|
|
@@ -576,8 +592,11 @@ async function openStreamBody(input) {
|
|
|
576
592
|
let lastBody;
|
|
577
593
|
let lastHeaders;
|
|
578
594
|
let retryDelayMs = openRetryPolicy.baseDelayMs;
|
|
595
|
+
const searchParams = {};
|
|
596
|
+
if (input.startIndex !== 0) searchParams.startIndex = String(input.startIndex);
|
|
597
|
+
if (input.requestTailIndex === true) searchParams.includeTailIndex = "1";
|
|
579
598
|
for (let attempt = 0; attempt < openRetryPolicy.maxAttempts; attempt += 1) {
|
|
580
|
-
const url = createClientUrl(input.host, createEveMessageStreamRoutePath(input.sessionId),
|
|
599
|
+
const url = createClientUrl(input.host, createEveMessageStreamRoutePath(input.sessionId), Object.keys(searchParams).length > 0 ? searchParams : void 0);
|
|
581
600
|
const headers = await input.resolveHeaders();
|
|
582
601
|
let response;
|
|
583
602
|
try {
|
|
@@ -594,7 +613,10 @@ async function openStreamBody(input) {
|
|
|
594
613
|
}
|
|
595
614
|
if (response.ok) {
|
|
596
615
|
if (!response.body) throw new ClientError(response.status, "Response body is null.", response.headers);
|
|
597
|
-
return
|
|
616
|
+
return {
|
|
617
|
+
body: response.body,
|
|
618
|
+
tailIndex: parseTailIndexHeader(response.headers)
|
|
619
|
+
};
|
|
598
620
|
}
|
|
599
621
|
lastStatus = response.status;
|
|
600
622
|
lastBody = await response.text();
|
|
@@ -607,6 +629,12 @@ async function openStreamBody(input) {
|
|
|
607
629
|
}
|
|
608
630
|
throw new ClientError(lastStatus ?? 0, lastBody ?? "Failed to open message stream.", lastHeaders);
|
|
609
631
|
}
|
|
632
|
+
function parseTailIndexHeader(headers) {
|
|
633
|
+
const raw = headers.get(EVE_STREAM_TAIL_INDEX_HEADER);
|
|
634
|
+
if (raw === null || !/^-?\d+$/.test(raw)) return;
|
|
635
|
+
const parsed = Number(raw);
|
|
636
|
+
return Number.isSafeInteger(parsed) ? parsed : void 0;
|
|
637
|
+
}
|
|
610
638
|
async function sleep$1(ms, signal) {
|
|
611
639
|
if (signal?.aborted) return;
|
|
612
640
|
await new Promise((resolve) => {
|
|
@@ -784,6 +812,7 @@ var ClientSession = class {
|
|
|
784
812
|
stream(options) {
|
|
785
813
|
const sessionId = this.#state.sessionId;
|
|
786
814
|
if (!sessionId) throw new Error("Session has no session ID. Send a message first.");
|
|
815
|
+
if (options?.follow === false && (options.startIndex ?? this.#state.streamIndex) < 0) throw new Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.");
|
|
787
816
|
return this.#streamAndAdvance(sessionId, options);
|
|
788
817
|
}
|
|
789
818
|
async #postTurn(input, session) {
|
|
@@ -845,6 +874,7 @@ var ClientSession = class {
|
|
|
845
874
|
const events = [];
|
|
846
875
|
try {
|
|
847
876
|
for await (const event of followStreamIterable({
|
|
877
|
+
follow: options?.follow,
|
|
848
878
|
host: this.#context.host,
|
|
849
879
|
resolveHeaders: () => this.#context.resolveHeaders(),
|
|
850
880
|
redirect: this.#context.redirect,
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Command } from "#compiled/commander/index.js";
|
|
2
|
+
interface RegistryCommandLogger {
|
|
3
|
+
error(message: string): void;
|
|
4
|
+
log(message: string): void;
|
|
5
|
+
}
|
|
6
|
+
/** Registers registry installation, configuration, and discovery commands. */
|
|
7
|
+
export declare function registerRegistryCommands(input: {
|
|
8
|
+
program: Command;
|
|
9
|
+
logger: RegistryCommandLogger;
|
|
10
|
+
appRoot: string;
|
|
11
|
+
}): void;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function registerRegistryCommands(e){let{appRoot:t,logger:n,program:r}=e;r.command(`add <item>`).description(`Install a registry item; relative paths use the official eve registry.`).option(`-o, --overwrite`,`Overwrite existing files.`).action(async(e,r)=>{let{runAddCommand:i}=await import(`./registry.js`);await i(n,t,e,r)});let i=r.command(`registry`).description(`Configure and browse extension and agent registry catalogs.`);i.command(`add <registries...>`).description(`Add registry namespace mappings to package.json.`).action(async e=>{let{runRegistryAddCommand:r}=await import(`./registry.js`);await r(n,t,e)}),i.command(`list`).description(`List items from all registries or one source.`).option(`-r, --registry <source>`,`List items from one registry.`).action(async e=>{let{runRegistryListCommand:r}=await import(`./registry.js`);await r(n,t,e.registry)}),i.command(`search <query>`).description(`Search all registries or one source.`).option(`-r, --registry <source>`,`Search one registry.`).action(async(e,r)=>{let{runRegistrySearchCommand:i}=await import(`./registry.js`);await i(n,t,e,r.registry)}),i.command(`view <item>`).description(`Print one registry item as JSON.`).action(async e=>{let{runRegistryViewCommand:r}=await import(`./registry.js`);await r(n,t,e)})}export{registerRegistryCommands};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { RegistryConfig } from "#compiled/shadcn-registry/index.js";
|
|
2
|
+
export interface AddRegistryMappingsResult {
|
|
3
|
+
added: string[];
|
|
4
|
+
skippedBuiltIn: string[];
|
|
5
|
+
skippedExisting: string[];
|
|
6
|
+
}
|
|
7
|
+
/** Reads registry namespace mappings from package.json. */
|
|
8
|
+
export declare function readRegistryConfig(appRoot: string): Promise<RegistryConfig>;
|
|
9
|
+
/** Adds explicit registry namespace mappings to package.json. */
|
|
10
|
+
export declare function addRegistryMappings(appRoot: string, arguments_: readonly string[]): Promise<AddRegistryMappingsResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{join}from"node:path";import{readFile,writeFile}from"node:fs/promises";function errorMessage(e){return e instanceof Error?e.message:String(e)}function isRegistrySource(e){return typeof e==`string`?!0:typeof e!=`object`||!e||!(`url`in e)?!1:typeof e.url==`string`}function parseRegistries(e,t){if(t===void 0)return{};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`${e} has an invalid registries field.`);let n={};for(let[r,i]of Object.entries(t)){if(!r.startsWith(`@`)||!isRegistrySource(i))throw Error(`${e} has an invalid registry entry for ${r}.`);n[r]=i}return n}async function readRegistryPackage(n){let r=join(n,`package.json`),i;try{i=JSON.parse(await readFile(r,`utf8`))}catch(e){throw Error(`Could not read ${r}: ${errorMessage(e)}`)}if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`${r} must contain a JSON object.`);let a=i;return{path:r,document:a,config:{registries:parseRegistries(r,a.registries)}}}function parseRegistryMapping(e){let t=e.indexOf(`=`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1);if(!n.startsWith(`@`))throw Error(`Registry namespaces must start with @: ${n}`);if(!r.includes(`{name}`))throw Error(`Pass a registry URL containing {name}, for example ${n}=https://example.com/r/{name}.json.`);return{namespace:n,url:r}}async function readRegistryConfig(e){return(await readRegistryPackage(e)).config}async function addRegistryMappings(e,t){if(t.length===0)throw Error(`Pass at least one registry to add.`);let r=await readRegistryPackage(e),i=t.map(parseRegistryMapping),a={...r.config.registries},o={added:[],skippedBuiltIn:[],skippedExisting:[]};for(let e of i)e.namespace===`@shadcn`?o.skippedBuiltIn.push(e.namespace):a[e.namespace]===void 0?(a[e.namespace]=e.url,o.added.push(e.namespace)):o.skippedExisting.push(e.namespace);return o.added.length>0&&await writeFile(r.path,`${JSON.stringify({...r.document,registries:a},null,2)}\n`,`utf8`),o}export{addRegistryMappings,readRegistryConfig};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface RegistryCommandLogger {
|
|
2
|
+
error(message: string): void;
|
|
3
|
+
log(message: string): void;
|
|
4
|
+
}
|
|
5
|
+
export interface AddCommandOptions {
|
|
6
|
+
overwrite?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Installs an official, configured, or URL-addressed registry item. */
|
|
9
|
+
export declare function runAddCommand(logger: RegistryCommandLogger, appRoot: string, item: string, options: AddCommandOptions): Promise<void>;
|
|
10
|
+
/** Adds registry namespace mappings to the project's package.json. */
|
|
11
|
+
export declare function runRegistryAddCommand(logger: RegistryCommandLogger, appRoot: string, mappings: readonly string[]): Promise<void>;
|
|
12
|
+
/** Lists registry items from every configured source or one selected source. */
|
|
13
|
+
export declare function runRegistryListCommand(logger: RegistryCommandLogger, appRoot: string, source?: string): Promise<void>;
|
|
14
|
+
/** Searches registry items across every configured source or one selected source. */
|
|
15
|
+
export declare function runRegistrySearchCommand(logger: RegistryCommandLogger, appRoot: string, query: string, source?: string): Promise<void>;
|
|
16
|
+
/** Prints one official, configured, or URL-addressed registry item as JSON. */
|
|
17
|
+
export declare function runRegistryViewCommand(logger: RegistryCommandLogger, appRoot: string, item: string): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{addRegistryMappings,readRegistryConfig}from"./registry-project.js";import{isEveProject}from"#setup/scaffold/index.js";import{addRegistryItems,getRegistryItems,searchRegistries}from"#compiled/shadcn-registry/index.js";const OFFICIAL_REGISTRY=`https://eve.dev/r`,OFFICIAL_CATALOG=`${OFFICIAL_REGISTRY}/registry.json`;function isRegistryAddress(e){return e.startsWith(`@`)||/^https?:\/\//.test(e)}function itemAddress(e){return isRegistryAddress(e)?e:`${OFFICIAL_REGISTRY}/${e}.json`}function errorMessage(e){return e instanceof Error?e.message:String(e)}async function runRegistryAction(t,n,i){if(!await isEveProject(n)){t.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}try{await i()}catch(e){t.error(errorMessage(e)),process.exitCode=1}}function configuredRegistrySources(e){return Object.keys(e.registries??{})}function validateRegistrySource(e){if(e!==void 0&&!isRegistryAddress(e))throw Error(`Registry sources must be a namespace or URL: ${e}`)}function printSearchResults(e,t){if(t.length===0){e.log(`No registry items found.`);return}for(let n of t)e.log(`${n.addCommandArgument}${n.description?` — ${n.description}`:``}`)}async function browseRegistryItems(e,t,r,i){validateRegistrySource(i);let a=await readRegistryConfig(t),s=i?[i]:[OFFICIAL_CATALOG,...configuredRegistrySources(a)],c=await searchRegistries(s,{config:a,continueOnError:s.length>1,query:r}),l=c.errors??[];l.length<s.length&&printSearchResults(e,c.items);for(let t of l)e.error(`${t.registry}: ${t.message}`);l.length>0&&(process.exitCode=1)}async function runAddCommand(e,t,r,a){await runRegistryAction(e,t,async()=>{let e=await readRegistryConfig(t);await addRegistryItems([itemAddress(r)],{...a,config:e,cwd:t})})}async function runRegistryAddCommand(e,n,r){await runRegistryAction(e,n,async()=>{let i=await addRegistryMappings(n,r);for(let t of i.skippedBuiltIn)e.log(`Skipped ${t} because it is built in.`);for(let t of i.skippedExisting)e.log(`Skipped ${t} because it is already configured.`);i.added.length>0&&e.log(`Added ${i.added.join(`, `)} to package.json.`)})}async function runRegistryListCommand(e,t,n){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,void 0,n))}async function runRegistrySearchCommand(e,t,n,r){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,n,r))}async function runRegistryViewCommand(e,t,r){await runRegistryAction(e,t,async()=>{let i=await readRegistryConfig(t),o=await getRegistryItems([itemAddress(r)],{config:i});e.log(JSON.stringify(o.length===1?o[0]:o,null,2))})}export{runAddCommand,runRegistryAddCommand,runRegistryListCommand,runRegistrySearchCommand,runRegistryViewCommand};
|
package/dist/src/cli/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{registerBuildCommand}from"#cli/commands/build.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{resolveDevUiMode,resolveTuiDisplayOptions}from"#cli/dev/ui-options.js";import{FORCED_EXIT_BACKSTOP_MS,installShutdownSignal,waitForShutdownSignal}from"#cli/shutdown.js";import{waitForServerOrStop,waitForUiOrServer}from"#cli/dev/wait-for-ui.js";import{parseDevelopmentHeaderOption,resolveDevelopmentUrlTarget}from"#cli/dev/url-target.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#cli/dev/local-server-process.js`)).createDevelopmentServer}const loadIsActiveDevelopmentServerForApp=async()=>(await import(`#internal/nitro/host.js`)).isActiveDevelopmentServerForApp;async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function createCliProgram(e,i){let c=resolveApplicationRoot(),g=resolveInstalledPackageInfo().version,_=new Command,
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{registerBuildCommand}from"#cli/commands/build.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{registerRegistryCommands}from"#cli/commands/register-registry-commands.js";import{resolveDevUiMode,resolveTuiDisplayOptions}from"#cli/dev/ui-options.js";import{FORCED_EXIT_BACKSTOP_MS,installShutdownSignal,waitForShutdownSignal}from"#cli/shutdown.js";import{waitForServerOrStop,waitForUiOrServer}from"#cli/dev/wait-for-ui.js";import{parseDevelopmentHeaderOption,resolveDevelopmentUrlTarget}from"#cli/dev/url-target.js";import{LOG_DISPLAY_MODES,parseLogDisplayMode}from"#cli/dev/tui/log-display-mode.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#cli/dev/local-server-process.js`)).createDevelopmentServer}const loadIsActiveDevelopmentServerForApp=async()=>(await import(`#internal/nitro/host.js`)).isActiveDevelopmentServerForApp;async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function shouldPrintCliBootBanner(e){return e.name()===`info`||e.name()===`dev`||e.name()===`init`}function parsePortOption(e){if(!/^-?\d+$/.test(e))throw new InvalidArgumentError(`Expected a numeric port, received "${e}".`);let t=Number(e);if(t<0||t>65535)throw new InvalidArgumentError(`Expected a port between 0 and 65535, received "${e}".`);return t}const DISPLAY_MODES=new Set([`full`,`collapsed`,`auto-collapsed`,`hidden`]),STATS_MODES=new Set([`tokens`,`tokensPerSecond`]);function parseDisplayMode(e){if(!DISPLAY_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...DISPLAY_MODES].join(`, `)}, received "${e}".`);return e}function parseStatsMode(e){if(!STATS_MODES.has(e))throw new InvalidArgumentError(`Expected one of ${[...STATS_MODES].join(`, `)}, received "${e}".`);return e}function parseLogsMode(e){let t=parseLogDisplayMode(e);if(t===void 0)throw new InvalidArgumentError(`Expected one of ${LOG_DISPLAY_MODES.join(`, `)}, received "${e}".`);return t}function parseContextSizeOption(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new InvalidArgumentError(`Expected a positive number, received "${e}".`);return t}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function createCliProgram(e,i){let c=resolveApplicationRoot(),g=resolveInstalledPackageInfo().version,_=new Command,v=createCliTheme();_.name(`eve`).description(`Build and run an eve application.`).version(g).showHelpAfterError().exitOverride().hook(`preAction`,(t,n)=>{shouldPrintCliBootBanner(n)&&e.log(eveCliBanner())}).configureOutput({writeErr:t=>{e.error(t.trimEnd())},writeOut:t=>{e.log(t.trimEnd())}});let y=_.command(`channels`).description(`Manage user-authored channels in the current project.`);y.command(`add [kind]`).description(`Add channels interactively, or scaffold a channel kind (slack | web).`).option(`-f, --force`,`Overwrite existing channel files`).option(`-y, --yes`,`Assume yes for confirmations; requires an explicit channel kind`).action(async(t,n)=>{let{runChannelsAddCommand:r}=await import(`#cli/commands/channels.js`);await r(e,c,{kind:t,options:n})}),y.command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async t=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(e,c,t)});let b=_.command(`extension`).description(`Create and build reusable eve extension packages.`);b.command(`init [target]`).description(`Create a new eve extension package.`).option(`-y, --yes`,`Accepted for compatibility; has no effect`).action(async(t,n)=>{n.yes&&e.error(`warning: --yes has no effect for eve extension init.`);let{runExtensionInitCommand:r}=await import(`#cli/commands/extension-init.js`);await r(e,c,t)}),b.command(`build`).description(`Build the current package as an eve extension.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);t(c);let{runExtensionBuildCommand:n}=await import(`#cli/commands/extension-build.js`);await n(e,c)}),registerRegistryCommands({program:_,logger:e,appRoot:c}),_.command(`init [target]`).description(`Create a new eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).option(`-y, --yes`,`Accepted for compatibility; has no effect`).action(async(t,n)=>{n.yes&&e.error(`warning: --yes has no effect for eve init.`);let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(e,c,t,{channelWebNextjs:n.channelWebNextjs})}),registerProjectCommands({program:_,logger:e,appRoot:c}),registerBuildCommand({appRoot:c,buildHost:i.buildHost,logger:e,program:_}),_.command(`start`).description(`Start a built eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async t=>{let{loadDevelopmentEnvironmentFiles:n}=await import(`#cli/dev/environment.js`);n(c);let a=await(i.startProductionHost??await loadStartProductionHost())(c,{host:t.host,port:t.port});e.log(renderCliTaggedLine(v,{message:`server listening at ${a.url}`,tag:`start`,tone:`success`})),await waitForShutdownSignal({close:()=>a.close(),wait:()=>a.wait()})}),_.command(`dev`).description(`Start the eve development server or connect to an existing URL.`).argument(`[url]`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 2000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`-H, --header <header>`,`Request header for a URL target, in "Name: value" form (repeatable)`,parseDevelopmentHeaderOption).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input, or start onboarding with /model`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
|
|
2
2
|
You can also pass a bare URL, for example: eve dev https://example.com
|
|
3
|
-
`).action(async(t,n)=>{let a=resolveDevelopmentUrlTarget(n,t),s=a?.serverUrl,u=hasInteractiveTerminal(),d=resolveDevUiMode({options:n,interactive:u});if(n.input!==void 0&&d===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let f=!1;s!==void 0&&(f=await(i.isActiveDevelopmentServerForApp??await loadIsActiveDevelopmentServerForApp())({appRoot:c,serverUrl:s}));let runInteractiveUi=async(e,t,r)=>{let o=await devBootPhase(`loading interactive UI`,async()=>i.runDevelopmentTui??await loadRunDevelopmentTui(),t),l=resolveTuiDisplayOptions(n),u=s===void 0||f?{kind:`local`,serverUrl:e.serverUrl,workspaceRoot:e.appRoot??c}:{kind:`remote`,serverUrl:e.serverUrl,workspaceRoot:c},d=resolveTuiTitle({name:n.name,target:u});d!==void 0&&(l.name=d);let p={target:u,initialInput:n.input,onBootProgress:t,lifecycle:r,...l};a?.headers===void 0?await o(p):await o({...p,headers:a.headers})};if(s){let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);if(t(c),e.log(`↗ ${f?`local`:`remote`} mode targeting ${
|
|
3
|
+
`).action(async(t,n)=>{let a=resolveDevelopmentUrlTarget(n,t),s=a?.serverUrl,u=hasInteractiveTerminal(),d=resolveDevUiMode({options:n,interactive:u});if(n.input!==void 0&&d===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let f=!1;s!==void 0&&(f=await(i.isActiveDevelopmentServerForApp??await loadIsActiveDevelopmentServerForApp())({appRoot:c,serverUrl:s}));let runInteractiveUi=async(e,t,r)=>{let o=await devBootPhase(`loading interactive UI`,async()=>i.runDevelopmentTui??await loadRunDevelopmentTui(),t),l=resolveTuiDisplayOptions(n),u=s===void 0||f?{kind:`local`,serverUrl:e.serverUrl,workspaceRoot:e.appRoot??c}:{kind:`remote`,serverUrl:e.serverUrl,workspaceRoot:c},d=resolveTuiTitle({name:n.name,target:u});d!==void 0&&(l.name=d);let p={target:u,initialInput:n.input,onBootProgress:t,lifecycle:r,...l};a?.headers===void 0?await o(p):await o({...p,headers:a.headers})};if(s){let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);if(t(c),e.log(`↗ ${f?`local`:`remote`} mode targeting ${v.info(new URL(s).host)}`),d===`headless`){e.log(renderCliTaggedLine(v,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}e.log(``);let n=installShutdownSignal({exitAfterMs:FORCED_EXIT_BACKSTOP_MS});try{await runInteractiveUi({serverUrl:s},void 0,n)}finally{n.dispose()}return}d===`tui`&&e.log(``);let p=d===`tui`?startCliLiveRow(e):void 0,m=createDevBootProgressReporter(p);p?.update(`Building your agent`);let h,g,closeServer=()=>h===void 0?Promise.resolve():(g??=h.close(),g.catch(()=>void 0),g),_=installShutdownSignal({exitAfterMs:FORCED_EXIT_BACKSTOP_MS,onStop:()=>{closeServer()}});try{h=(i.startHost??await loadStartHost())(c,{existing:d===`tui`?`attach-if-unconfigured`:`reject`,host:n.host,onBootProgress:m,port:n.port});let t=(await Promise.race([h.start().then(e=>({handle:e})),_.stopped.then(()=>({handle:void 0}))])).handle;if(t===void 0)return;if(d!==`tui`&&e.log(renderCliTaggedLine(v,{message:`server listening at ${t.url}`,tag:`dev`,tone:`success`})),d===`headless`){n.ui!==!1&&!u&&e.log(renderCliTaggedLine(v,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForServerOrStop(h,_);return}await waitForUiOrServer({handle:t,lifecycle:_,server:h,runUi:async()=>await runInteractiveUi({appRoot:t.appRoot,serverUrl:t.url},m,_)})}finally{p?.stop(),await closeServer(),_.dispose()}});let x=_.command(`logs`).description("Inspect local `eve dev` diagnostic logs (.eve/logs).");return x.command(`show [logid]`,{isDefault:!0}).description(`Print a diagnostic log (the most recent when logid is omitted).`).option(`--dump`,`Prepend the log's environment dump (.dump sibling)`).option(`--events`,`Interleave session events from the local workflow store`).action(async(t,n)=>{let{runLogsShowCommand:r}=await import(`#cli/commands/logs.js`);await r(e,c,t,n)}),x.command(`ls`).description(`List diagnostic logs, most recent first.`).option(`--json`,`Output as JSON`).action(async t=>{let{runLogsListCommand:n}=await import(`#cli/commands/logs.js`);await n(e,c,t)}),_.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(i.printApplicationInfo??await loadPrintApplicationInfo())(e,c,t)}),_.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,n)=>{await(i.runEvalCommand??await loadRunEvalCommand())(t,n,e)}),_}async function runCli(e=process.argv.slice(2),t=console,n={}){let r=createCliProgram(t,n),a=e.length===0?[`dev`]:e;try{await r.parseAsync(a,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;let r=await(n.isCodingAgentLaunch??isCodingAgentLaunch)();if(a[0]===`init`&&r){let{initAgentInstructions:e}=await import(`#cli/commands/agent-instructions.js`);t.log(e())}throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,runCli};
|
|
@@ -21,6 +21,12 @@ interface FollowStreamInput {
|
|
|
21
21
|
readonly sessionId: string;
|
|
22
22
|
readonly signal?: AbortSignal;
|
|
23
23
|
readonly startIndex: number;
|
|
24
|
+
/** Follow the live stream after the durable tail (default). `false` bounds the read at the tail. */
|
|
25
|
+
readonly follow?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** One connection open; `requestTailIndex` asks the server to report the durable tail index. */
|
|
28
|
+
interface OpenStreamInput extends FollowStreamInput {
|
|
29
|
+
readonly requestTailIndex?: boolean;
|
|
24
30
|
}
|
|
25
31
|
/**
|
|
26
32
|
* Follows a session's durable event stream from an absolute cursor,
|
|
@@ -30,15 +36,24 @@ interface FollowStreamInput {
|
|
|
30
36
|
* idle budget; repeated empty streams eventually stop the follow. Callers own
|
|
31
37
|
* boundary handling. Negative tail-relative cursors use one connection because
|
|
32
38
|
* they cannot be advanced safely.
|
|
39
|
+
*
|
|
40
|
+
* With `follow: false`, the first connection fixes the bound: the iterator
|
|
41
|
+
* yields events until the cursor passes that tail, reconnecting as needed,
|
|
42
|
+
* then returns instead of following.
|
|
33
43
|
*/
|
|
34
44
|
export declare function followStreamIterable(input: FollowStreamInput): AsyncGenerator<HandleMessageStreamEvent>;
|
|
45
|
+
/** An opened connection: the response body plus the tail index from the response header, if any. */
|
|
46
|
+
interface OpenedStream {
|
|
47
|
+
readonly body: ReadableStream<Uint8Array>;
|
|
48
|
+
readonly tailIndex: number | undefined;
|
|
49
|
+
}
|
|
35
50
|
/**
|
|
36
51
|
* Opens one stream response body, retrying transient failures with capped
|
|
37
52
|
* exponential backoff (~35s total): brief network outages and the short
|
|
38
53
|
* propagation window where a just-acknowledged session may not yet be
|
|
39
54
|
* readable from the stream route.
|
|
40
55
|
*/
|
|
41
|
-
export declare function openStreamBody(input:
|
|
56
|
+
export declare function openStreamBody(input: OpenStreamInput & {
|
|
42
57
|
readonly retryPolicy?: ResolvedStreamReconnectPolicy;
|
|
43
|
-
}): Promise<
|
|
58
|
+
}): Promise<OpenedStream>;
|
|
44
59
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveMessageStreamRoutePath}from"#protocol/routes.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){let
|
|
1
|
+
import{createEveMessageStreamRoutePath}from"#protocol/routes.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let n=resolveStreamReconnectPolicy(e.streamReconnectPolicy),r=n.streamIdleReconnectPolicy,a=e.startIndex,o=r.baseDelayMs,s=0,c=!0,l;for(;;){let u;try{u=await openStreamBody({...e,retryPolicy:n,startIndex:a,requestTailIndex:e.follow===!1&&l===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if(e.follow===!1&&l===void 0&&(l=u.tailIndex,l===void 0))throw await u.body.cancel().catch(()=>{}),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(l!==void 0&&a>l){await u.body.cancel().catch(()=>{});return}let d=!1;try{for await(let e of readNdjsonStream(u.body))if(a+=1,d=!0,o=r.baseDelayMs,s=0,yield e,l!==void 0&&a>l)return}catch(e){if(!isStreamDisconnectError(e))throw e}if(e.signal?.aborted||e.startIndex<0||r.maxAttempts===0||!d&&!c&&(s+=1)>=r.maxAttempts||(c=!1,await sleep(o,e.signal),e.signal?.aborted))return;o=Math.min(o*2,r.maxDelayMs)}}async function openStreamBody(t){let i=t.retryPolicy??DEFAULT_STREAM_RECONNECT_POLICY,o=i.streamOpenReconnectPolicy,s,c,l,u=o.baseDelayMs,d={};t.startIndex!==0&&(d.startIndex=String(t.startIndex)),t.requestTailIndex===!0&&(d.includeTailIndex=`1`);for(let a=0;a<o.maxAttempts;a+=1){let f=createClientUrl(t.host,createEveMessageStreamRoutePath(t.sessionId),Object.keys(d).length>0?d:void 0),p=await t.resolveHeaders(),m;try{m=await fetch(f,{headers:p,redirect:t.redirect,signal:t.signal??null})}catch(e){if(t.signal?.aborted||!isStreamDisconnectError(e)||a===o.maxAttempts-1)throw e;await sleep(u,t.signal),u=Math.min(u*2,o.maxDelayMs);continue}if(m.ok){if(!m.body)throw new ClientError(m.status,`Response body is null.`,m.headers);return{body:m.body,tailIndex:parseTailIndexHeader(m.headers)}}if(s=m.status,c=await m.text(),l=m.headers,!i.retryableErrorStatuses.has(m.status))throw new ClientError(m.status,c,m.headers);a<o.maxAttempts-1&&(await sleep(u,t.signal),u=Math.min(u*2,o.maxDelayMs))}throw new ClientError(s??0,c??`Failed to open message stream.`,l)}function parseTailIndexHeader(e){let n=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(n===null||!/^-?\d+$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{followStreamIterable,openStreamBody};
|
|
@@ -72,8 +72,12 @@ export declare class ClientSession {
|
|
|
72
72
|
* one connection. Negative indices read relative to the current tail on one connection
|
|
73
73
|
* and do not advance the stored absolute cursor.
|
|
74
74
|
*
|
|
75
|
+
* Pass `follow: false` for a bounded read: yields events up to the durable
|
|
76
|
+
* tail observed when the stream opens, then returns instead of following.
|
|
77
|
+
* The stored cursor still advances past the consumed events.
|
|
78
|
+
*
|
|
75
79
|
* @throws {Error} If the session has no session ID (no message has been sent
|
|
76
|
-
* yet)
|
|
80
|
+
* yet), or if `follow: false` is combined with a negative `startIndex`.
|
|
77
81
|
*/
|
|
78
82
|
stream(options?: StreamOptions): AsyncIterable<HandleMessageStreamEvent>;
|
|
79
83
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_CREATE_SESSION_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{advanceSession,createInitialSessionState}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{ResetResponseSchema}from"#protocol/reset-session.js";import{followStreamIterable}from"#client/open-stream.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);if(this.#t===n){let e={...n,sessionId:i};r!==void 0&&(e.continuationToken=r),this.#t=e}return new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}async cancel(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);let r=createClientUrl(this.#e.host,createEveCancelTurnRoutePath(t)),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let a=await fetch(r,withRedirectPolicy({headers:i,method:`POST`,body:e?JSON.stringify(e):void 0},this.#e.redirect)),s=await a.text();if(!a.ok)throw new ClientError(a.status,s,a.headers);let c;try{c=JSON.parse(s)}catch{throw Error(`Cancel route returned invalid JSON (${a.status}).`)}let l=CancelTurnResponseSchema.safeParse(c);if(!l.success||l.data.sessionId!==t)throw Error(`Cancel route returned an invalid response (${a.status}).`);return{sessionId:l.data.sessionId,status:l.data.status}}async reset(){let e=this.#t,n=e.continuationToken;if(n===void 0){if(e.sessionId!==void 0)throw Error(`Session has no continuation token. Consume its event stream before resetting.`);return this.#t=createInitialSessionState(),{status:`no_active_session`}}let r=createClientUrl(this.#e.host,EVE_RESET_SESSION_ROUTE_PATH),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let a=await fetch(r,withRedirectPolicy({body:JSON.stringify({continuationToken:n}),headers:i,method:`POST`},this.#e.redirect)),s=await a.text();if(!a.ok)throw new ClientError(a.status,s,a.headers);let l;try{l=JSON.parse(s)}catch{throw Error(`Reset route returned invalid JSON (${a.status}).`)}let u=ResetResponseSchema.safeParse(l);if(!u.success||u.data.status===`reset`&&e.sessionId!==void 0&&u.data.previousSessionId!==e.sessionId)throw Error(`Reset route returned an invalid response (${a.status}).`);return this.#t===e&&(this.#t=createInitialSessionState()),u.data.status===`reset`?{previousSessionId:u.data.previousSessionId,status:`reset`}:{status:`no_active_session`}}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return this.#i(t,e)}async#n(t,n){let a=n.sessionId?createEveContinueSessionRoutePath(n.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,o=createClientUrl(this.#e.host,a),s=await this.#e.resolveHeaders(t.headers);s.set(`content-type`,`application/json`);let c=createHandleMessageBody({input:t,outputSchema:serializeOutputSchema(t.outputSchema),session:n});if(c===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let l=await postTurnWithRetry({body:JSON.stringify(c),headers:s,mustDeliver:(t.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:t.signal,url:o}),u=await l.json(),d=(typeof u.sessionId==`string`?u.sessionId:void 0)??l.headers.get(EVE_SESSION_ID_HEADER)?.trim()??n.sessionId;if(!d)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof u.continuationToken==`string`?u.continuationToken:void 0,sessionId:d}}async*#r(e,t,n,r){let i=[];try{for await(let t of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r.headers),redirect:this.#e.redirect,streamReconnectPolicy:r.streamReconnectPolicy,sessionId:e,signal:r.signal,startIndex:n.sessionId===e?n.streamIndex:0}))if(i.push(t),yield t,isCurrentTurnBoundaryEvent(t))break}finally{this.#t=advanceSession({continuationToken:t,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async*#i(e,t){let n=this.#t,r=t?.startIndex??n.streamIndex,i=[];try{for await(let n of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,streamReconnectPolicy:t?.streamReconnectPolicy,sessionId:e,signal:t?.signal,startIndex:r}))i.push(n),yield n}finally{r>=0&&(this.#t=advanceSession({continuationToken:n.continuationToken,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:r},sessionId:e}))}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,n,r,i;for(let a=0;a<t;a+=1){let s=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(s.ok)return s;if(n=s.status,r=await s.text(),i=s.headers,!isRetryableDeliveryFailure(s.status,r))throw new ClientError(s.status,r,s.headers);a<t-1&&await sleep(200)}throw new ClientError(n??0,r??`Failed to deliver session turn.`,i)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{ClientSession};
|
|
1
|
+
import{EVE_CREATE_SESSION_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{advanceSession,createInitialSessionState}from"#client/session-utils.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{CancelTurnResponseSchema}from"#protocol/cancel-turn.js";import{ResetResponseSchema}from"#protocol/reset-session.js";import{followStreamIterable}from"#client/open-stream.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async send(e){let t=normalizeSendTurnInput(e),n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(t,n);if(this.#t===n){let e={...n,sessionId:i};r!==void 0&&(e.continuationToken=r),this.#t=e}return new MessageResponse({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}async cancel(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);let r=createClientUrl(this.#e.host,createEveCancelTurnRoutePath(t)),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let a=await fetch(r,withRedirectPolicy({headers:i,method:`POST`,body:e?JSON.stringify(e):void 0},this.#e.redirect)),s=await a.text();if(!a.ok)throw new ClientError(a.status,s,a.headers);let c;try{c=JSON.parse(s)}catch{throw Error(`Cancel route returned invalid JSON (${a.status}).`)}let l=CancelTurnResponseSchema.safeParse(c);if(!l.success||l.data.sessionId!==t)throw Error(`Cancel route returned an invalid response (${a.status}).`);return{sessionId:l.data.sessionId,status:l.data.status}}async reset(){let e=this.#t,n=e.continuationToken;if(n===void 0){if(e.sessionId!==void 0)throw Error(`Session has no continuation token. Consume its event stream before resetting.`);return this.#t=createInitialSessionState(),{status:`no_active_session`}}let r=createClientUrl(this.#e.host,EVE_RESET_SESSION_ROUTE_PATH),i=await this.#e.resolveHeaders();i.set(`content-type`,`application/json`);let a=await fetch(r,withRedirectPolicy({body:JSON.stringify({continuationToken:n}),headers:i,method:`POST`},this.#e.redirect)),s=await a.text();if(!a.ok)throw new ClientError(a.status,s,a.headers);let l;try{l=JSON.parse(s)}catch{throw Error(`Reset route returned invalid JSON (${a.status}).`)}let u=ResetResponseSchema.safeParse(l);if(!u.success||u.data.status===`reset`&&e.sessionId!==void 0&&u.data.previousSessionId!==e.sessionId)throw Error(`Reset route returned an invalid response (${a.status}).`);return this.#t===e&&(this.#t=createInitialSessionState()),u.data.status===`reset`?{previousSessionId:u.data.previousSessionId,status:`reset`}:{status:`no_active_session`}}stream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#i(t,e)}async#n(t,n){let a=n.sessionId?createEveContinueSessionRoutePath(n.sessionId):EVE_CREATE_SESSION_ROUTE_PATH,o=createClientUrl(this.#e.host,a),s=await this.#e.resolveHeaders(t.headers);s.set(`content-type`,`application/json`);let c=createHandleMessageBody({input:t,outputSchema:serializeOutputSchema(t.outputSchema),session:n});if(c===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let l=await postTurnWithRetry({body:JSON.stringify(c),headers:s,mustDeliver:(t.inputResponses?.length??0)>0,redirect:this.#e.redirect,signal:t.signal,url:o}),u=await l.json(),d=(typeof u.sessionId==`string`?u.sessionId:void 0)??l.headers.get(EVE_SESSION_ID_HEADER)?.trim()??n.sessionId;if(!d)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof u.continuationToken==`string`?u.continuationToken:void 0,sessionId:d}}async*#r(e,t,n,r){let i=[];try{for await(let t of followStreamIterable({host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(r.headers),redirect:this.#e.redirect,streamReconnectPolicy:r.streamReconnectPolicy,sessionId:e,signal:r.signal,startIndex:n.sessionId===e?n.streamIndex:0}))if(i.push(t),yield t,isCurrentTurnBoundaryEvent(t))break}finally{this.#t=advanceSession({continuationToken:t,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,sessionId:e,session:n})}}async*#i(e,t){let n=this.#t,r=t?.startIndex??n.streamIndex,i=[];try{for await(let n of followStreamIterable({follow:t?.follow,host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(),redirect:this.#e.redirect,streamReconnectPolicy:t?.streamReconnectPolicy,sessionId:e,signal:t?.signal,startIndex:r}))i.push(n),yield n}finally{r>=0&&(this.#t=advanceSession({continuationToken:n.continuationToken,events:i,preserveCompletedSessions:this.#e.preserveCompletedSessions,session:{...n,sessionId:e,streamIndex:r},sessionId:e}))}}};async function postTurnWithRetry(e){let t=e.mustDeliver?10:1,n,r,i;for(let a=0;a<t;a+=1){let s=await fetch(e.url,{body:e.body,headers:e.headers,method:`POST`,redirect:e.redirect,signal:e.signal??null});if(s.ok)return s;if(n=s.status,r=await s.text(),i=s.headers,!isRetryableDeliveryFailure(s.status,r))throw new ClientError(s.status,r,s.headers);a<t-1&&await sleep(200)}throw new ClientError(n??0,r??`Failed to deliver session turn.`,i)}function isRetryableDeliveryFailure(e,t){return e===500&&/target session was not found/i.test(t)}async function sleep(e){await new Promise(t=>setTimeout(t,e))}function normalizeSendTurnInput(e){return typeof e==`string`?{message:e}:e}function createHandleMessageBody(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.input.clientContext!==void 0&&(t.clientContext=e.input.clientContext),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||e.session.continuationToken!==void 0&&t.message===void 0&&t.inputResponses===void 0?null:t}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{ClientSession};
|
|
@@ -171,6 +171,13 @@ export interface StreamOptions {
|
|
|
171
171
|
* not reconnect automatically because their absolute cursor is unknown.
|
|
172
172
|
*/
|
|
173
173
|
readonly startIndex?: number;
|
|
174
|
+
/**
|
|
175
|
+
* Follow the live stream after the durable tail (default). Pass `false`
|
|
176
|
+
* for a bounded catch-up read: yields events until the cursor passes the
|
|
177
|
+
* tail observed when the stream opened, then returns instead of
|
|
178
|
+
* following. Requires a nonnegative start cursor.
|
|
179
|
+
*/
|
|
180
|
+
readonly follow?: boolean;
|
|
174
181
|
/**
|
|
175
182
|
* Abort signal for cancelling the stream.
|
|
176
183
|
*/
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
"@ai-sdk/provider": "4.0.3",
|
|
25
25
|
"@ai-sdk/provider-utils": "5.0.12",
|
|
26
26
|
"semver": "7.8.4",
|
|
27
|
+
"shadcn": "4.16.0",
|
|
27
28
|
"@standard-schema/spec": "1.1.0",
|
|
28
29
|
"turndown": "7.2.4",
|
|
29
30
|
"@vercel/detect-agent": "1.2.3",
|
|
@@ -38,5 +39,5 @@
|
|
|
38
39
|
"zod": "4.4.3",
|
|
39
40
|
"zod-validation-error": "5.0.0"
|
|
40
41
|
},
|
|
41
|
-
"scriptHash": "
|
|
42
|
+
"scriptHash": "4e3efe4ec9d4f103e4736b56f0f69e210bcef5e1e215d1eaa6a335bbea500083"
|
|
42
43
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 shadcn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export type RegistrySource =
|
|
2
|
+
| string
|
|
3
|
+
| {
|
|
4
|
+
url: string;
|
|
5
|
+
params?: Record<string, string>;
|
|
6
|
+
headers?: Record<string, string>;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export interface RegistryConfig {
|
|
10
|
+
registries?: Record<string, RegistrySource>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface AddRegistryItemsOptions {
|
|
14
|
+
cwd?: string;
|
|
15
|
+
config?: RegistryConfig;
|
|
16
|
+
overwrite?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface RegistrySearchItem {
|
|
20
|
+
registry: string;
|
|
21
|
+
name: string;
|
|
22
|
+
addCommandArgument: string;
|
|
23
|
+
type?: string;
|
|
24
|
+
description?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RegistrySearchResult {
|
|
28
|
+
items: RegistrySearchItem[];
|
|
29
|
+
pagination: {
|
|
30
|
+
total: number;
|
|
31
|
+
offset: number;
|
|
32
|
+
limit: number;
|
|
33
|
+
hasMore: boolean;
|
|
34
|
+
};
|
|
35
|
+
errors?: Array<{ message: string; registry: string }>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function addRegistryItems(items: string[], options?: AddRegistryItemsOptions): Promise<void>;
|
|
39
|
+
|
|
40
|
+
export function getRegistryItems(
|
|
41
|
+
items: string[],
|
|
42
|
+
options?: { config?: RegistryConfig; useCache?: boolean },
|
|
43
|
+
): Promise<unknown[]>;
|
|
44
|
+
|
|
45
|
+
export function searchRegistries(
|
|
46
|
+
registries: string[],
|
|
47
|
+
options?: {
|
|
48
|
+
query?: string;
|
|
49
|
+
types?: string[];
|
|
50
|
+
limit?: number;
|
|
51
|
+
offset?: number;
|
|
52
|
+
config?: RegistryConfig;
|
|
53
|
+
useCache?: boolean;
|
|
54
|
+
continueOnError?: boolean;
|
|
55
|
+
},
|
|
56
|
+
): Promise<RegistrySearchResult>;
|