@tangle-network/agent-app 0.50.4 → 0.50.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +1 -1
- package/dist/chat-routes/index.js +22 -12
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/sandbox-producer.d.ts +4 -0
- package/dist/{chunk-KJEW23GR.js → chunk-3MIQCPUX.js} +2 -2
- package/dist/{chunk-DEXBRUZR.js → chunk-63EKFZOE.js} +31 -5
- package/dist/chunk-63EKFZOE.js.map +1 -0
- package/dist/{chunk-3NM4GCAY.js → chunk-DPO7FGCN.js} +9 -6
- package/dist/chunk-DPO7FGCN.js.map +1 -0
- package/dist/{chunk-TFW7OB4L.js → chunk-P5ZJQKOI.js} +3 -2
- package/dist/{chunk-TFW7OB4L.js.map → chunk-P5ZJQKOI.js.map} +1 -1
- package/dist/model-resolution/failover.d.ts +6 -0
- package/dist/model-resolution/index.js +1 -1
- package/dist/public-consultation/index.js +2 -2
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/recovery.d.ts +2 -0
- package/dist/stream/index.js +1 -1
- package/dist/stream/turn-identity.d.ts +16 -11
- package/dist/teams/index.js +5 -5
- package/dist/teams/invitations-api.js +4 -4
- package/dist/web-react/index.js +3 -3
- package/dist/workspace-apps/index.d.ts +66 -0
- package/dist/workspace-apps/index.js +99 -0
- package/dist/workspace-apps/index.js.map +1 -0
- package/dist/workspace-react/index.d.ts +15 -1
- package/dist/workspace-react/index.js +28 -7
- package/dist/workspace-react/index.js.map +1 -1
- package/package.json +6 -1
- package/dist/chunk-3NM4GCAY.js.map +0 -1
- package/dist/chunk-DEXBRUZR.js.map +0 -1
- /package/dist/{chunk-KJEW23GR.js.map → chunk-3MIQCPUX.js.map} +0 -0
|
@@ -38,6 +38,8 @@ export declare const UPSTREAM_UNAVAILABLE_STATUSES: readonly number[];
|
|
|
38
38
|
* scan would read a token count or a duration as a status.
|
|
39
39
|
*/
|
|
40
40
|
export declare function readHttpStatusHint(text: string): number | undefined;
|
|
41
|
+
/** Read a recognized upstream code, including the terminal message-only shape. */
|
|
42
|
+
export declare function readUpstreamUnavailableCode(signal: unknown): string | undefined;
|
|
41
43
|
/**
|
|
42
44
|
* True when `signal` — a thrown error OR a resolved result payload — indicates
|
|
43
45
|
* the model's upstream is unavailable and another model is worth trying.
|
|
@@ -54,6 +56,8 @@ export interface ModelFailoverAttempt {
|
|
|
54
56
|
ok: boolean;
|
|
55
57
|
/** Why this model was abandoned. Absent when `ok`. */
|
|
56
58
|
reason?: string;
|
|
59
|
+
/** Recognized upstream code carried by this failed attempt. */
|
|
60
|
+
errorCode?: string;
|
|
57
61
|
}
|
|
58
62
|
/** The outcome of a failover run: the value plus the full attempt trail. */
|
|
59
63
|
export interface ModelFailoverResult<T> {
|
|
@@ -67,6 +71,8 @@ export interface ModelFailoverResult<T> {
|
|
|
67
71
|
/** Every model in the chain failed; carries the trail for logging. */
|
|
68
72
|
export declare class ModelFailoverExhaustedError extends Error {
|
|
69
73
|
readonly attempts: ModelFailoverAttempt[];
|
|
74
|
+
/** Last recognized upstream code across the exhausted chain, when present. */
|
|
75
|
+
readonly upstreamCode?: string;
|
|
70
76
|
constructor(attempts: ModelFailoverAttempt[]);
|
|
71
77
|
}
|
|
72
78
|
/** Inputs to {@link runWithModelFailover}. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createChatTurnRoutes,
|
|
3
3
|
streamChatRouteAsSandboxEvents
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-3MIQCPUX.js";
|
|
5
5
|
import "../chunk-TZEEGDHS.js";
|
|
6
6
|
import "../chunk-3NCPXNBZ.js";
|
|
7
7
|
import "../chunk-ZSSCVT6H.js";
|
|
@@ -9,7 +9,7 @@ import "../chunk-RACQDXJ7.js";
|
|
|
9
9
|
import "../chunk-X47R2IVO.js";
|
|
10
10
|
import "../chunk-ZVEEWGDK.js";
|
|
11
11
|
import "../chunk-TXD5HXLE.js";
|
|
12
|
-
import "../chunk-
|
|
12
|
+
import "../chunk-DPO7FGCN.js";
|
|
13
13
|
import "../chunk-MX55JP7D.js";
|
|
14
14
|
import "../chunk-YJMCRXQQ.js";
|
|
15
15
|
import "../chunk-M3K2HVQD.js";
|
package/dist/sandbox/index.js
CHANGED
|
@@ -99,7 +99,7 @@ import {
|
|
|
99
99
|
workspaceSandboxRecoveryMessage,
|
|
100
100
|
workspaceSandboxRecoveryRecommendedActions,
|
|
101
101
|
writeProfileFilesToBox
|
|
102
|
-
} from "../chunk-
|
|
102
|
+
} from "../chunk-P5ZJQKOI.js";
|
|
103
103
|
import "../chunk-MCYJON3F.js";
|
|
104
104
|
import "../chunk-LWSJK546.js";
|
|
105
105
|
import "../chunk-FZOGDD2E.js";
|
|
@@ -205,6 +205,8 @@ export interface WorkspaceSandboxRecoveryManager<Snapshot extends WorkspaceSandb
|
|
|
205
205
|
complete: (args: {
|
|
206
206
|
workspaceId: string;
|
|
207
207
|
replacementSandboxId: string;
|
|
208
|
+
/** The key used by this provisioning attempt, not a freshly read successor. */
|
|
209
|
+
replacementBoxKey?: string;
|
|
208
210
|
}) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>;
|
|
209
211
|
}
|
|
210
212
|
/** Bind canonical recovery policy to the application's existing storage. */
|
package/dist/stream/index.js
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import type { JsonRecord } from './stream-normalizer';
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
id: string;
|
|
5
|
-
role: 'user' | 'assistant' | 'system' | 'tool';
|
|
6
|
-
content: string;
|
|
2
|
+
/** Minimum read-only shape; typed chat parts need no dictionary index signature. */
|
|
3
|
+
interface TurnIdentityMessage {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly role: 'user' | 'assistant' | 'system' | 'tool';
|
|
6
|
+
readonly content: string;
|
|
7
|
+
readonly parts: readonly object[] | null;
|
|
8
|
+
}
|
|
9
|
+
/** Retained compatibility shape for callers using unstructured message records. */
|
|
10
|
+
export interface PersistedChatMessageForTurn extends TurnIdentityMessage {
|
|
7
11
|
parts: Array<Record<string, unknown>> | null;
|
|
8
12
|
}
|
|
9
13
|
/** Represent a chat turn with resolved user message insertion and prior message context */
|
|
10
|
-
export interface ResolvedChatTurn {
|
|
14
|
+
export interface ResolvedChatTurn<Message extends TurnIdentityMessage = PersistedChatMessageForTurn> {
|
|
11
15
|
turnIndex: number;
|
|
12
16
|
shouldInsertUserMessage: boolean;
|
|
13
|
-
priorMessages:
|
|
17
|
+
priorMessages: Message[];
|
|
14
18
|
userParts: JsonRecord[];
|
|
15
19
|
/** The id of the user row this turn REUSES (retry dedup), when one was
|
|
16
20
|
* found. Absent on the insert path, where no row exists yet.
|
|
@@ -25,10 +29,10 @@ export declare function normalizeClientTurnId(value: unknown): string | undefine
|
|
|
25
29
|
/** Build an array of text parts with optional turn ID for user input */
|
|
26
30
|
export declare function buildUserTextParts(text: string, turnId: string | undefined): JsonRecord[];
|
|
27
31
|
/** Resolve whether a message contains any part with the specified turn ID */
|
|
28
|
-
export declare function messageHasTurnId(message:
|
|
32
|
+
export declare function messageHasTurnId(message: Pick<TurnIdentityMessage, 'parts'>, turnId: string): boolean;
|
|
29
33
|
/** Resolve a chat turn by determining message reuse and constructing user message parts */
|
|
30
|
-
export declare function resolveChatTurn(input: {
|
|
31
|
-
existingMessages:
|
|
34
|
+
export declare function resolveChatTurn<Message extends TurnIdentityMessage>(input: {
|
|
35
|
+
existingMessages: readonly Message[];
|
|
32
36
|
userContent: string;
|
|
33
37
|
turnId?: string;
|
|
34
38
|
/** True when the thread has a turn still RUNNING in the turn-event buffer
|
|
@@ -46,4 +50,5 @@ export declare function resolveChatTurn(input: {
|
|
|
46
50
|
* assistant row trailing a SETTLED turn is a completed answer (stop — the
|
|
47
51
|
* user genuinely repeated a message and deserves a new turn). */
|
|
48
52
|
hasRunningTurn?: boolean;
|
|
49
|
-
}): ResolvedChatTurn
|
|
53
|
+
}): ResolvedChatTurn<Message>;
|
|
54
|
+
export {};
|
package/dist/teams/index.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateInviteToken,
|
|
3
|
+
isInviteTokenShape,
|
|
4
|
+
validateInviteToken
|
|
5
|
+
} from "../chunk-DJ4VJIH5.js";
|
|
1
6
|
import {
|
|
2
7
|
INVITATION_EXPIRY_DAYS,
|
|
3
8
|
generateInvitationToken,
|
|
@@ -7,11 +12,6 @@ import {
|
|
|
7
12
|
parseInvitationPermission,
|
|
8
13
|
renderInvitationEmail
|
|
9
14
|
} from "../chunk-2DRYTJHI.js";
|
|
10
|
-
import {
|
|
11
|
-
generateInviteToken,
|
|
12
|
-
isInviteTokenShape,
|
|
13
|
-
validateInviteToken
|
|
14
|
-
} from "../chunk-DJ4VJIH5.js";
|
|
15
15
|
import {
|
|
16
16
|
ASSIGNABLE_WORKSPACE_ROLES,
|
|
17
17
|
ORGANIZATION_ROLES,
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SeatLimitError
|
|
3
|
+
} from "../chunk-MEUNTJL5.js";
|
|
4
|
+
import "../chunk-DJ4VJIH5.js";
|
|
1
5
|
import {
|
|
2
6
|
generateInvitationToken,
|
|
3
7
|
getInvitationExpiresAt,
|
|
@@ -5,10 +9,6 @@ import {
|
|
|
5
9
|
normalizeInvitationEmail,
|
|
6
10
|
parseInvitationPermission
|
|
7
11
|
} from "../chunk-2DRYTJHI.js";
|
|
8
|
-
import {
|
|
9
|
-
SeatLimitError
|
|
10
|
-
} from "../chunk-MEUNTJL5.js";
|
|
11
|
-
import "../chunk-DJ4VJIH5.js";
|
|
12
12
|
import {
|
|
13
13
|
hasWorkspaceRole
|
|
14
14
|
} from "../chunk-6XIAPIW6.js";
|
package/dist/web-react/index.js
CHANGED
|
@@ -129,9 +129,6 @@ import {
|
|
|
129
129
|
withoutRecordGridRemoved,
|
|
130
130
|
withoutRecordGridUpdate
|
|
131
131
|
} from "../chunk-5DEQ2FJK.js";
|
|
132
|
-
import {
|
|
133
|
-
MENTION_PILL_CLASS
|
|
134
|
-
} from "../chunk-3HUFJ5LO.js";
|
|
135
132
|
import {
|
|
136
133
|
SessionHistoryPanel,
|
|
137
134
|
formatSessionTimestamp,
|
|
@@ -139,6 +136,9 @@ import {
|
|
|
139
136
|
useSessionActions,
|
|
140
137
|
useSessionHistory
|
|
141
138
|
} from "../chunk-F32T3DRJ.js";
|
|
139
|
+
import {
|
|
140
|
+
MENTION_PILL_CLASS
|
|
141
|
+
} from "../chunk-3HUFJ5LO.js";
|
|
142
142
|
import "../chunk-FBVLEGEG.js";
|
|
143
143
|
import {
|
|
144
144
|
EvidenceLineageTable,
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** A sandbox app registered in one product workspace. Products persist and authorize these rows. */
|
|
2
|
+
export interface WorkspaceAppRecord {
|
|
3
|
+
id: string;
|
|
4
|
+
workspaceId: string;
|
|
5
|
+
name: string;
|
|
6
|
+
sandboxId: string;
|
|
7
|
+
previewId: string;
|
|
8
|
+
port: number;
|
|
9
|
+
previewUrl: string;
|
|
10
|
+
status: 'starting' | 'ready' | 'unavailable';
|
|
11
|
+
createdAt: string;
|
|
12
|
+
updatedAt: string;
|
|
13
|
+
}
|
|
14
|
+
/** Structural shape returned by the Sandbox SDK previewLinks API. */
|
|
15
|
+
export interface WorkspaceAppPreviewLink {
|
|
16
|
+
previewId: string;
|
|
17
|
+
sandboxId: string;
|
|
18
|
+
port: number;
|
|
19
|
+
protocol: 'tcp' | 'udp';
|
|
20
|
+
hostname: string;
|
|
21
|
+
url: string;
|
|
22
|
+
status: 'provisioning' | 'ready' | 'error' | 'disabled';
|
|
23
|
+
}
|
|
24
|
+
export interface WorkspaceAppIdentity {
|
|
25
|
+
/** Assigned by the product, stable across preview updates and deliberate republishes. */
|
|
26
|
+
id: string;
|
|
27
|
+
/** Taken from the authenticated route or session, never agent tool arguments. */
|
|
28
|
+
workspaceId: string;
|
|
29
|
+
/** Current box resolved by the product from that workspace or session. */
|
|
30
|
+
sandboxId: string;
|
|
31
|
+
name: string;
|
|
32
|
+
/** Preserve this when republishing the same app onto a replacement sandbox. */
|
|
33
|
+
createdAt?: string;
|
|
34
|
+
updatedAt?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Build a durable registration from a preview link created on the box that
|
|
38
|
+
* the authenticated product request resolved. The product owns row identity,
|
|
39
|
+
* access policy, persistence, and the decision to publish.
|
|
40
|
+
*/
|
|
41
|
+
export declare function workspaceAppFromPreviewLink(identity: WorkspaceAppIdentity, link: WorkspaceAppPreviewLink): WorkspaceAppRecord;
|
|
42
|
+
export interface WorkspaceAppHttpProof {
|
|
43
|
+
/** The exact trusted SDK preview URL requested by the server. */
|
|
44
|
+
previewUrl: string;
|
|
45
|
+
status: number;
|
|
46
|
+
contentType: string;
|
|
47
|
+
/** Number of bytes read from the response body, excluding headers. */
|
|
48
|
+
bodyBytes: number;
|
|
49
|
+
checkedAt: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Mark an app ready only after the host fetched its HTML over the trusted
|
|
53
|
+
* preview URL. The host owns the request timeout, redirect and credential
|
|
54
|
+
* policy, authorization, and compare-and-swap storage update.
|
|
55
|
+
*/
|
|
56
|
+
export declare function confirmWorkspaceAppReady(app: WorkspaceAppRecord, proof: WorkspaceAppHttpProof): WorkspaceAppRecord;
|
|
57
|
+
/** Refresh delivery state without changing which sandbox service this app means. */
|
|
58
|
+
export declare function refreshWorkspaceAppPreview(app: WorkspaceAppRecord, link: WorkspaceAppPreviewLink, updatedAt?: string): WorkspaceAppRecord;
|
|
59
|
+
export interface WorkspaceAppBuilderInstructionsOptions {
|
|
60
|
+
/** Host tool that writes or updates the app registration after creating a preview link. */
|
|
61
|
+
publishTool: string;
|
|
62
|
+
/** Optional host tool for finding app IDs the builder may update. */
|
|
63
|
+
listTool?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Portable instructions for an agent profile that builds workspace apps. */
|
|
66
|
+
export declare function workspaceAppBuilderInstructions({ publishTool, listTool, }: WorkspaceAppBuilderInstructionsOptions): string[];
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// src/workspace-apps/index.ts
|
|
2
|
+
function nonempty(value, field) {
|
|
3
|
+
if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
4
|
+
throw new Error("Invalid workspace app " + field);
|
|
5
|
+
}
|
|
6
|
+
return value.trim();
|
|
7
|
+
}
|
|
8
|
+
function checkedLink(link, sandboxId) {
|
|
9
|
+
if (link.sandboxId !== sandboxId) {
|
|
10
|
+
throw new Error("Preview link belongs to another sandbox");
|
|
11
|
+
}
|
|
12
|
+
nonempty(link.previewId, "previewId");
|
|
13
|
+
if (link.protocol !== "tcp") throw new Error("Workspace app preview must use TCP");
|
|
14
|
+
if (!Number.isInteger(link.port) || link.port < 1 || link.port > 65535) {
|
|
15
|
+
throw new Error("Invalid workspace app port");
|
|
16
|
+
}
|
|
17
|
+
if (!["provisioning", "ready", "error", "disabled"].includes(link.status)) {
|
|
18
|
+
throw new Error("Invalid workspace app preview status");
|
|
19
|
+
}
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = new URL(link.url);
|
|
23
|
+
} catch {
|
|
24
|
+
throw new Error("Invalid workspace app preview URL");
|
|
25
|
+
}
|
|
26
|
+
if (url.protocol !== "https:" || !url.hostname || url.hostname !== link.hostname || url.username || url.password || url.search || url.hash) {
|
|
27
|
+
throw new Error("Invalid workspace app preview URL");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function appStatus(status) {
|
|
31
|
+
if (status === "ready" || status === "provisioning") return "starting";
|
|
32
|
+
return "unavailable";
|
|
33
|
+
}
|
|
34
|
+
function workspaceAppFromPreviewLink(identity, link) {
|
|
35
|
+
const sandboxId = nonempty(identity.sandboxId, "sandboxId");
|
|
36
|
+
checkedLink(link, sandboxId);
|
|
37
|
+
const timestamp = identity.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
38
|
+
return {
|
|
39
|
+
id: nonempty(identity.id, "id"),
|
|
40
|
+
workspaceId: nonempty(identity.workspaceId, "workspaceId"),
|
|
41
|
+
name: nonempty(identity.name, "name"),
|
|
42
|
+
sandboxId,
|
|
43
|
+
previewId: link.previewId,
|
|
44
|
+
port: link.port,
|
|
45
|
+
previewUrl: link.url,
|
|
46
|
+
status: appStatus(link.status),
|
|
47
|
+
createdAt: identity.createdAt ?? timestamp,
|
|
48
|
+
updatedAt: timestamp
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function confirmWorkspaceAppReady(app, proof) {
|
|
52
|
+
if (proof.previewUrl !== app.previewUrl || proof.status !== 200 || !/^text\/html(?:\s*;|\s*$)/i.test(proof.contentType) || !Number.isInteger(proof.bodyBytes) || proof.bodyBytes < 1 || !Number.isFinite(Date.parse(proof.checkedAt))) {
|
|
53
|
+
throw new Error("Workspace app HTML preview is not ready");
|
|
54
|
+
}
|
|
55
|
+
return { ...app, status: "ready", updatedAt: proof.checkedAt };
|
|
56
|
+
}
|
|
57
|
+
function refreshWorkspaceAppPreview(app, link, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
58
|
+
checkedLink(link, app.sandboxId);
|
|
59
|
+
if (link.previewId !== app.previewId || link.port !== app.port) {
|
|
60
|
+
throw new Error("Preview link does not match workspace app");
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
...app,
|
|
64
|
+
previewUrl: link.url,
|
|
65
|
+
status: appStatus(link.status),
|
|
66
|
+
updatedAt
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function toolName(value) {
|
|
70
|
+
if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(value)) {
|
|
71
|
+
throw new Error("Invalid workspace app tool name");
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
function workspaceAppBuilderInstructions({
|
|
76
|
+
publishTool,
|
|
77
|
+
listTool
|
|
78
|
+
}) {
|
|
79
|
+
const publish = toolName(publishTool);
|
|
80
|
+
const list = listTool ? toolName(listTool) : void 0;
|
|
81
|
+
return [
|
|
82
|
+
"Build a working HTTP application in the current sandbox when the user asks for an app.",
|
|
83
|
+
...list ? ["Use " + list + " to inspect the existing apps before creating or updating one."] : [],
|
|
84
|
+
"Start its server on 0.0.0.0 using an available, unclaimed port.",
|
|
85
|
+
"Call " + publish + " with the app name, stable app ID when updating, and listening port.",
|
|
86
|
+
"Use the host tool result as the source of the registered app URL and status; never invent a preview URL.",
|
|
87
|
+
"Keep the same app ID for later revisions of that app.",
|
|
88
|
+
"Treat a preview link as public. Do not embed secrets or private business facts in client code or responses.",
|
|
89
|
+
"Read real business data through authorized product APIs. Do not fabricate records to make the app look complete.",
|
|
90
|
+
"Report the app as available only after the host confirms its preview is ready."
|
|
91
|
+
];
|
|
92
|
+
}
|
|
93
|
+
export {
|
|
94
|
+
confirmWorkspaceAppReady,
|
|
95
|
+
refreshWorkspaceAppPreview,
|
|
96
|
+
workspaceAppBuilderInstructions,
|
|
97
|
+
workspaceAppFromPreviewLink
|
|
98
|
+
};
|
|
99
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/workspace-apps/index.ts"],"sourcesContent":["/** A sandbox app registered in one product workspace. Products persist and authorize these rows. */\nexport interface WorkspaceAppRecord {\n id: string\n workspaceId: string\n name: string\n sandboxId: string\n previewId: string\n port: number\n previewUrl: string\n status: 'starting' | 'ready' | 'unavailable'\n createdAt: string\n updatedAt: string\n}\n\n/** Structural shape returned by the Sandbox SDK previewLinks API. */\nexport interface WorkspaceAppPreviewLink {\n previewId: string\n sandboxId: string\n port: number\n protocol: 'tcp' | 'udp'\n hostname: string\n url: string\n status: 'provisioning' | 'ready' | 'error' | 'disabled'\n}\n\nexport interface WorkspaceAppIdentity {\n /** Assigned by the product, stable across preview updates and deliberate republishes. */\n id: string\n /** Taken from the authenticated route or session, never agent tool arguments. */\n workspaceId: string\n /** Current box resolved by the product from that workspace or session. */\n sandboxId: string\n name: string\n /** Preserve this when republishing the same app onto a replacement sandbox. */\n createdAt?: string\n updatedAt?: string\n}\n\nfunction nonempty(value: string, field: string): string {\n if (typeof value !== 'string' || !value.trim() || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error('Invalid workspace app ' + field)\n }\n return value.trim()\n}\n\nfunction checkedLink(link: WorkspaceAppPreviewLink, sandboxId: string): void {\n if (link.sandboxId !== sandboxId) {\n throw new Error('Preview link belongs to another sandbox')\n }\n nonempty(link.previewId, 'previewId')\n if (link.protocol !== 'tcp') throw new Error('Workspace app preview must use TCP')\n if (!Number.isInteger(link.port) || link.port < 1 || link.port > 65535) {\n throw new Error('Invalid workspace app port')\n }\n if (!['provisioning', 'ready', 'error', 'disabled'].includes(link.status)) {\n throw new Error('Invalid workspace app preview status')\n }\n let url: URL\n try {\n url = new URL(link.url)\n } catch {\n throw new Error('Invalid workspace app preview URL')\n }\n if (\n url.protocol !== 'https:' ||\n !url.hostname ||\n url.hostname !== link.hostname ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n throw new Error('Invalid workspace app preview URL')\n }\n}\n\nfunction appStatus(status: WorkspaceAppPreviewLink['status']): WorkspaceAppRecord['status'] {\n if (status === 'ready' || status === 'provisioning') return 'starting'\n return 'unavailable'\n}\n\n/**\n * Build a durable registration from a preview link created on the box that\n * the authenticated product request resolved. The product owns row identity,\n * access policy, persistence, and the decision to publish.\n */\nexport function workspaceAppFromPreviewLink(\n identity: WorkspaceAppIdentity,\n link: WorkspaceAppPreviewLink,\n): WorkspaceAppRecord {\n const sandboxId = nonempty(identity.sandboxId, 'sandboxId')\n checkedLink(link, sandboxId)\n const timestamp = identity.updatedAt ?? new Date().toISOString()\n return {\n id: nonempty(identity.id, 'id'),\n workspaceId: nonempty(identity.workspaceId, 'workspaceId'),\n name: nonempty(identity.name, 'name'),\n sandboxId,\n previewId: link.previewId,\n port: link.port,\n previewUrl: link.url,\n status: appStatus(link.status),\n createdAt: identity.createdAt ?? timestamp,\n updatedAt: timestamp,\n }\n}\n\nexport interface WorkspaceAppHttpProof {\n /** The exact trusted SDK preview URL requested by the server. */\n previewUrl: string\n status: number\n contentType: string\n /** Number of bytes read from the response body, excluding headers. */\n bodyBytes: number\n checkedAt: string\n}\n\n/**\n * Mark an app ready only after the host fetched its HTML over the trusted\n * preview URL. The host owns the request timeout, redirect and credential\n * policy, authorization, and compare-and-swap storage update.\n */\nexport function confirmWorkspaceAppReady(\n app: WorkspaceAppRecord,\n proof: WorkspaceAppHttpProof,\n): WorkspaceAppRecord {\n if (\n proof.previewUrl !== app.previewUrl ||\n proof.status !== 200 ||\n !/^text\\/html(?:\\s*;|\\s*$)/i.test(proof.contentType) ||\n !Number.isInteger(proof.bodyBytes) ||\n proof.bodyBytes < 1 ||\n !Number.isFinite(Date.parse(proof.checkedAt))\n ) {\n throw new Error('Workspace app HTML preview is not ready')\n }\n return { ...app, status: 'ready', updatedAt: proof.checkedAt }\n}\n\n/** Refresh delivery state without changing which sandbox service this app means. */\nexport function refreshWorkspaceAppPreview(\n app: WorkspaceAppRecord,\n link: WorkspaceAppPreviewLink,\n updatedAt = new Date().toISOString(),\n): WorkspaceAppRecord {\n checkedLink(link, app.sandboxId)\n if (link.previewId !== app.previewId || link.port !== app.port) {\n throw new Error('Preview link does not match workspace app')\n }\n return {\n ...app,\n previewUrl: link.url,\n status: appStatus(link.status),\n updatedAt,\n }\n}\n\nexport interface WorkspaceAppBuilderInstructionsOptions {\n /** Host tool that writes or updates the app registration after creating a preview link. */\n publishTool: string\n /** Optional host tool for finding app IDs the builder may update. */\n listTool?: string\n}\n\nfunction toolName(value: string): string {\n if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(value)) {\n throw new Error('Invalid workspace app tool name')\n }\n return value\n}\n\n/** Portable instructions for an agent profile that builds workspace apps. */\nexport function workspaceAppBuilderInstructions({\n publishTool,\n listTool,\n}: WorkspaceAppBuilderInstructionsOptions): string[] {\n const publish = toolName(publishTool)\n const list = listTool ? toolName(listTool) : undefined\n return [\n 'Build a working HTTP application in the current sandbox when the user asks for an app.',\n ...(list ? ['Use ' + list + ' to inspect the existing apps before creating or updating one.'] : []),\n 'Start its server on 0.0.0.0 using an available, unclaimed port.',\n 'Call ' + publish + ' with the app name, stable app ID when updating, and listening port.',\n 'Use the host tool result as the source of the registered app URL and status; never invent a preview URL.',\n 'Keep the same app ID for later revisions of that app.',\n 'Treat a preview link as public. Do not embed secrets or private business facts in client code or responses.',\n 'Read real business data through authorized product APIs. Do not fabricate records to make the app look complete.',\n 'Report the app as available only after the host confirms its preview is ready.',\n ]\n}\n"],"mappings":";AAsCA,SAAS,SAAS,OAAe,OAAuB;AACtD,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,wBAAwB,KAAK,KAAK,GAAG;AACrF,UAAM,IAAI,MAAM,2BAA2B,KAAK;AAAA,EAClD;AACA,SAAO,MAAM,KAAK;AACpB;AAEA,SAAS,YAAY,MAA+B,WAAyB;AAC3E,MAAI,KAAK,cAAc,WAAW;AAChC,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AACA,WAAS,KAAK,WAAW,WAAW;AACpC,MAAI,KAAK,aAAa,MAAO,OAAM,IAAI,MAAM,oCAAoC;AACjF,MAAI,CAAC,OAAO,UAAU,KAAK,IAAI,KAAK,KAAK,OAAO,KAAK,KAAK,OAAO,OAAO;AACtE,UAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C;AACA,MAAI,CAAC,CAAC,gBAAgB,SAAS,SAAS,UAAU,EAAE,SAAS,KAAK,MAAM,GAAG;AACzE,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACA,MAAI;AACJ,MAAI;AACF,UAAM,IAAI,IAAI,KAAK,GAAG;AAAA,EACxB,QAAQ;AACN,UAAM,IAAI,MAAM,m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S,IAAI,MAAM;AAC9D,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY,KAAK;AAAA,IACjB,QAAQ,UAAU,KAAK,MAAM;AAAA,IAC7B;AAAA,EACF;AACF;AASA,SAAS,SAAS,OAAuB;AACvC,MAAI,CAAC,4BAA4B,KAAK,KAAK,GAAG;AAC5C,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO;AACT;AAGO,SAAS,gCAAgC;AAAA,EAC9C;AAAA,EACA;AACF,GAAqD;AACnD,QAAM,UAAU,SAAS,WAAW;AACpC,QAAM,OAAO,WAAW,SAAS,QAAQ,IAAI;AAC7C,SAAO;AAAA,IACL;AAAA,IACA,GAAI,OAAO,CAAC,SAAS,OAAO,gEAAgE,IAAI,CAAC;AAAA,IACjG;AAAA,IACA,UAAU,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard';
|
|
2
2
|
import type { ReactNode } from 'react';
|
|
3
|
+
import type { WorkspaceAppRecord } from '../workspace-apps';
|
|
3
4
|
import { type NavRouteDef, type RailPrefetch, type SessionRowActions, type SessionSummary } from '../session-shell';
|
|
4
5
|
type WorkspaceIcon = SidebarLayoutNavItem['icon'];
|
|
5
6
|
/** The session data and product-owned URLs needed by the default workspace. */
|
|
@@ -43,6 +44,17 @@ export interface AgentWorkspaceSessionConfig {
|
|
|
43
44
|
/** Whether History starts expanded. Defaults to `true`. */
|
|
44
45
|
defaultOpen?: boolean;
|
|
45
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Registered apps shown as individual workspace destinations.
|
|
49
|
+
* Products supply authorized rows and their real route; preview URLs never
|
|
50
|
+
* become navigation hrefs.
|
|
51
|
+
*/
|
|
52
|
+
export interface AgentWorkspaceAppsConfig {
|
|
53
|
+
icon: WorkspaceIcon;
|
|
54
|
+
items: readonly Pick<WorkspaceAppRecord, 'id' | 'name'>[];
|
|
55
|
+
hrefForApp: (appId: string) => string;
|
|
56
|
+
prefetch?: RailPrefetch;
|
|
57
|
+
}
|
|
46
58
|
/** Route data for the shared active-nav resolver. */
|
|
47
59
|
export interface AgentWorkspaceActiveRoute {
|
|
48
60
|
/** Current browser pathname, including the product's workspace base. */
|
|
@@ -62,6 +74,8 @@ export interface AgentWorkspaceLayoutProps extends Omit<SidebarLayoutProps, 'act
|
|
|
62
74
|
navItems: SidebarLayoutNavItem[];
|
|
63
75
|
/** Omit for a workflow-only shell with no conversational session rail. */
|
|
64
76
|
sessions?: AgentWorkspaceSessionConfig;
|
|
77
|
+
/** Registered app destinations, in the product's persisted order. */
|
|
78
|
+
apps?: AgentWorkspaceAppsConfig;
|
|
65
79
|
/** When supplied, active navigation is resolved by the shared route rules. */
|
|
66
80
|
activeRoute?: AgentWorkspaceActiveRoute;
|
|
67
81
|
/** Escape hatch for routers that already resolved the active item. */
|
|
@@ -82,5 +96,5 @@ export interface AgentWorkspaceLayoutProps extends Omit<SidebarLayoutProps, 'act
|
|
|
82
96
|
* with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first
|
|
83
97
|
* structure.
|
|
84
98
|
*/
|
|
85
|
-
export declare function AgentWorkspaceLayout({ children, navItems, sessions, activeRoute, activeId, ...sidebarProps }: AgentWorkspaceLayoutProps): import("react").JSX.Element;
|
|
99
|
+
export declare function AgentWorkspaceLayout({ children, navItems, sessions, apps, activeRoute, activeId, ...sidebarProps }: AgentWorkspaceLayoutProps): import("react").JSX.Element;
|
|
86
100
|
export {};
|
|
@@ -18,6 +18,7 @@ function AgentWorkspaceLayout({
|
|
|
18
18
|
children,
|
|
19
19
|
navItems,
|
|
20
20
|
sessions,
|
|
21
|
+
apps,
|
|
21
22
|
activeRoute,
|
|
22
23
|
activeId,
|
|
23
24
|
...sidebarProps
|
|
@@ -49,17 +50,37 @@ function AgentWorkspaceLayout({
|
|
|
49
50
|
defaultOpen: sessions.defaultOpen
|
|
50
51
|
});
|
|
51
52
|
})() : void 0;
|
|
52
|
-
const
|
|
53
|
+
const appNavItems = (apps?.items ?? []).map((app) => {
|
|
54
|
+
const href = apps.hrefForApp(app.id);
|
|
55
|
+
if (!href.startsWith("/") || href.startsWith("//") || /[?#\\]/.test(href)) {
|
|
56
|
+
throw new Error("Workspace app href must be a local route path");
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
id: "workspace-app:" + app.id,
|
|
60
|
+
label: app.name,
|
|
61
|
+
icon: apps.icon,
|
|
62
|
+
href,
|
|
63
|
+
prefetch: apps.prefetch
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const workspaceNavItems = [
|
|
67
|
+
...navItems,
|
|
68
|
+
...appNavItems,
|
|
69
|
+
...sessionNav ? [sessionNav] : []
|
|
70
|
+
];
|
|
71
|
+
const appRoutes = activeRoute ? appNavItems.map((item) => {
|
|
72
|
+
const path = routePathFromHref(item.href, activeRoute.base);
|
|
73
|
+
if (!path) throw new Error("Workspace app href must be under the active workspace");
|
|
74
|
+
return { id: item.id, path };
|
|
75
|
+
}) : [];
|
|
53
76
|
const historyRoutePath = sessions && activeRoute ? routePathFromHref(sessions.href, activeRoute.base) : null;
|
|
54
77
|
const resolvedActiveId = activeRoute ? resolveActiveNavId({
|
|
55
78
|
...activeRoute,
|
|
56
|
-
routes:
|
|
79
|
+
routes: [
|
|
57
80
|
...activeRoute.routes,
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
] : activeRoute.routes
|
|
81
|
+
...appRoutes,
|
|
82
|
+
...sessionNav && historyRoutePath ? [{ id: sessions?.id ?? "history", path: historyRoutePath }] : []
|
|
83
|
+
]
|
|
63
84
|
}) : activeId;
|
|
64
85
|
const layoutProps = {
|
|
65
86
|
hideBelow: "lg",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workspace-react/index.tsx"],"sourcesContent":["import { SidebarLayout, type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard'\nimport type { ReactNode } from 'react'\n\nimport {\n buildSessionNavItem,\n composeSidebarSessions,\n resolveActiveNavId,\n type NavRouteDef,\n type RailPrefetch,\n type SessionRowActions,\n type SessionSummary,\n} from '../session-shell'\n\ntype WorkspaceIcon = SidebarLayoutNavItem['icon']\n\nfunction routePathFromHref(href: string, base: string): string | null {\n const path = href.split(/[?#]/, 1)[0] ?? ''\n const root = base.replace(/\\/+$/, '')\n if (path === root) return '/'\n if (!path.startsWith(`${root}/`)) return null\n return path.slice(root.length)\n}\n\n/** The session data and product-owned URLs needed by the default workspace. */\nexport interface AgentWorkspaceSessionConfig {\n /** Icon shown beside the expandable History row. */\n icon: WorkspaceIcon\n /** Id for the session row; defaults to `history`. */\n id?: string\n /** Product copy for the session row; defaults to `History`. */\n label?: string\n /** Full-history route used by the row and overflow item. */\n href: string\n /** Product-owned URL for an individual session. */\n hrefForSession: (sessionId: string) => string\n /** Server-loaded rows, ordered by the product's query. */\n sessions: SessionSummary[]\n /** Sessions created by another tab before the loader revalidates. */\n optimisticSessions?: SessionSummary[]\n /** Number of rows shown in the rail before the full-history link. */\n limit?: number\n /** Total persisted session count, used to decide whether overflow exists. */\n totalCount?: number\n /** Session currently open in the route. */\n activeSessionId?: string | null\n /** Sessions with a live turn. */\n respondingSessionIds?: ReadonlySet<string>\n /** Live unread ids from the product's event channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** Optional product-owned rename/delete/pin actions. */\n actions?: SessionRowActions<WorkspaceIcon>\n /** Label for the overflow row. Defaults to `View all chats`. */\n overflowLabel?: string\n /** Empty state for the expanded rail row. Defaults to `No chats yet`. */\n emptyLabel?: string\n /** Fallback title for untitled sessions. */\n untitledLabel?: string\n /** Router prefetch behavior for session links. */\n prefetch?: RailPrefetch\n /** Whether History starts expanded. Defaults to `true`. */\n defaultOpen?: boolean\n}\n\n/** Route data for the shared active-nav resolver. */\nexport interface AgentWorkspaceActiveRoute {\n /** Current browser pathname, including the product's workspace base. */\n pathname: string\n /** Product route root, for example `/app/ws_123`. */\n base: string\n /** Product-owned rail routes, relative to `base`. */\n routes: NavRouteDef[]\n /** Extra route prefixes that should highlight an existing row. */\n aliases?: Record<string, string>\n /** Route prefixes that intentionally highlight no row. */\n claimsNothing?: string[]\n}\n\nexport interface AgentWorkspaceLayoutProps\n extends Omit<SidebarLayoutProps, 'activeId' | 'children' | 'navItems' | 'hideBelow' | 'railLabels'> {\n children: ReactNode\n /** Product-owned destinations. The shared History row is appended after them. */\n navItems: SidebarLayoutNavItem[]\n /** Omit for a workflow-only shell with no conversational session rail. */\n sessions?: AgentWorkspaceSessionConfig\n /** When supplied, active navigation is resolved by the shared route rules. */\n activeRoute?: AgentWorkspaceActiveRoute\n /** Escape hatch for routers that already resolved the active item. */\n activeId?: string\n /** Hide the fixed desktop rail below this breakpoint. Defaults to `lg`. */\n hideBelow?: SidebarLayoutProps['hideBelow']\n /** Show labels beside rail icons. Defaults to `true`. */\n railLabels?: SidebarLayoutProps['railLabels']\n}\n\n/**\n * The default agent workspace composition.\n *\n * Products own their navigation taxonomy, routes, and session storage. This\n * component owns the repeated assembly: the standard visual layout, the\n * expandable History row, capped session composition, unread state, and active\n * route resolution. The full History route and the empty-state composer stay\n * separate because their data and domain copy belong to the product; pair this\n * with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first\n * structure.\n */\nexport function AgentWorkspaceLayout({\n children,\n navItems,\n sessions,\n activeRoute,\n activeId,\n ...sidebarProps\n}: AgentWorkspaceLayoutProps) {\n const sessionNav = sessions\n ? (() => {\n const composed = composeSidebarSessions({\n loaderSessions: sessions.sessions,\n optimisticSessions: sessions.optimisticSessions,\n limit: sessions.limit ?? 20,\n totalCount: sessions.totalCount,\n liveUnreadIds: sessions.liveUnreadIds,\n locallyReadIds: sessions.locallyReadIds,\n currentSessionId: sessions.activeSessionId,\n })\n\n return buildSessionNavItem<WorkspaceIcon>({\n id: sessions.id,\n label: sessions.label,\n icon: sessions.icon,\n href: sessions.href,\n sessions: composed.sessions,\n hrefForSession: sessions.hrefForSession,\n activeSessionId: sessions.activeSessionId,\n respondingSessionIds: sessions.respondingSessionIds,\n actions: sessions.actions,\n overflow: composed.hasMore\n ? { href: sessions.href, label: sessions.overflowLabel }\n : undefined,\n emptyLabel: sessions.emptyLabel,\n untitledLabel: sessions.untitledLabel,\n prefetch: sessions.prefetch,\n defaultOpen: sessions.defaultOpen,\n })\n })()\n : undefined\n\n const workspaceNavItems: SidebarLayoutNavItem[] = sessionNav\n ? [...navItems, sessionNav]\n : navItems\n\n const historyRoutePath = sessions && activeRoute\n ? routePathFromHref(sessions.href, activeRoute.base)\n : null\n\n const resolvedActiveId = activeRoute\n ? resolveActiveNavId({\n ...activeRoute,\n routes: sessionNav && historyRoutePath\n ? [\n ...activeRoute.routes,\n {\n id: sessions?.id ?? 'history',\n path: historyRoutePath,\n },\n ]\n : activeRoute.routes,\n })\n : activeId\n\n const layoutProps = {\n hideBelow: 'lg' as const,\n railLabels: true,\n ...sidebarProps,\n }\n\n return (\n <SidebarLayout\n {...layoutProps}\n navItems={workspaceNavItems}\n activeId={resolvedActiveId}\n >\n {children}\n </SidebarLayout>\n )\n}\n"],"mappings":";;;;;;;AAAA,SAAS,qBAAyE;AAkL9E;AAnKJ,SAAS,kBAAkB,MAAc,MAA6B;AACpE,QAAM,OAAO,KAAK,MAAM,QAAQ,CAAC,EAAE,CAAC,KAAK;AACzC,QAAM,OAAO,KAAK,QAAQ,QAAQ,EAAE;AACpC,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,EAAG,QAAO;AACzC,SAAO,KAAK,MAAM,KAAK,MAAM;AAC/B;AAsFO,SAAS,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AAAA,EACL;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU;AAAA,MACV,UAAU;AAAA,MAET;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/workspace-react/index.tsx"],"sourcesContent":["import { SidebarLayout, type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard'\nimport type { ReactNode } from 'react'\n\nimport type { WorkspaceAppRecord } from '../workspace-apps'\n\nimport {\n buildSessionNavItem,\n composeSidebarSessions,\n resolveActiveNavId,\n type NavRouteDef,\n type RailPrefetch,\n type SessionRowActions,\n type SessionSummary,\n} from '../session-shell'\n\ntype WorkspaceIcon = SidebarLayoutNavItem['icon']\n\nfunction routePathFromHref(href: string, base: string): string | null {\n const path = href.split(/[?#]/, 1)[0] ?? ''\n const root = base.replace(/\\/+$/, '')\n if (path === root) return '/'\n if (!path.startsWith(`${root}/`)) return null\n return path.slice(root.length)\n}\n\n/** The session data and product-owned URLs needed by the default workspace. */\nexport interface AgentWorkspaceSessionConfig {\n /** Icon shown beside the expandable History row. */\n icon: WorkspaceIcon\n /** Id for the session row; defaults to `history`. */\n id?: string\n /** Product copy for the session row; defaults to `History`. */\n label?: string\n /** Full-history route used by the row and overflow item. */\n href: string\n /** Product-owned URL for an individual session. */\n hrefForSession: (sessionId: string) => string\n /** Server-loaded rows, ordered by the product's query. */\n sessions: SessionSummary[]\n /** Sessions created by another tab before the loader revalidates. */\n optimisticSessions?: SessionSummary[]\n /** Number of rows shown in the rail before the full-history link. */\n limit?: number\n /** Total persisted session count, used to decide whether overflow exists. */\n totalCount?: number\n /** Session currently open in the route. */\n activeSessionId?: string | null\n /** Sessions with a live turn. */\n respondingSessionIds?: ReadonlySet<string>\n /** Live unread ids from the product's event channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** Optional product-owned rename/delete/pin actions. */\n actions?: SessionRowActions<WorkspaceIcon>\n /** Label for the overflow row. Defaults to `View all chats`. */\n overflowLabel?: string\n /** Empty state for the expanded rail row. Defaults to `No chats yet`. */\n emptyLabel?: string\n /** Fallback title for untitled sessions. */\n untitledLabel?: string\n /** Router prefetch behavior for session links. */\n prefetch?: RailPrefetch\n /** Whether History starts expanded. Defaults to `true`. */\n defaultOpen?: boolean\n}\n\n/**\n * Registered apps shown as individual workspace destinations.\n * Products supply authorized rows and their real route; preview URLs never\n * become navigation hrefs.\n */\nexport interface AgentWorkspaceAppsConfig {\n icon: WorkspaceIcon\n items: readonly Pick<WorkspaceAppRecord, 'id' | 'name'>[]\n hrefForApp: (appId: string) => string\n prefetch?: RailPrefetch\n}\n\n/** Route data for the shared active-nav resolver. */\nexport interface AgentWorkspaceActiveRoute {\n /** Current browser pathname, including the product's workspace base. */\n pathname: string\n /** Product route root, for example `/app/ws_123`. */\n base: string\n /** Product-owned rail routes, relative to `base`. */\n routes: NavRouteDef[]\n /** Extra route prefixes that should highlight an existing row. */\n aliases?: Record<string, string>\n /** Route prefixes that intentionally highlight no row. */\n claimsNothing?: string[]\n}\n\nexport interface AgentWorkspaceLayoutProps\n extends Omit<SidebarLayoutProps, 'activeId' | 'children' | 'navItems' | 'hideBelow' | 'railLabels'> {\n children: ReactNode\n /** Product-owned destinations. The shared History row is appended after them. */\n navItems: SidebarLayoutNavItem[]\n /** Omit for a workflow-only shell with no conversational session rail. */\n sessions?: AgentWorkspaceSessionConfig\n /** Registered app destinations, in the product's persisted order. */\n apps?: AgentWorkspaceAppsConfig\n /** When supplied, active navigation is resolved by the shared route rules. */\n activeRoute?: AgentWorkspaceActiveRoute\n /** Escape hatch for routers that already resolved the active item. */\n activeId?: string\n /** Hide the fixed desktop rail below this breakpoint. Defaults to `lg`. */\n hideBelow?: SidebarLayoutProps['hideBelow']\n /** Show labels beside rail icons. Defaults to `true`. */\n railLabels?: SidebarLayoutProps['railLabels']\n}\n\n/**\n * The default agent workspace composition.\n *\n * Products own their navigation taxonomy, routes, and session storage. This\n * component owns the repeated assembly: the standard visual layout, the\n * expandable History row, capped session composition, unread state, and active\n * route resolution. The full History route and the empty-state composer stay\n * separate because their data and domain copy belong to the product; pair this\n * with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first\n * structure.\n */\nexport function AgentWorkspaceLayout({\n children,\n navItems,\n sessions,\n apps,\n activeRoute,\n activeId,\n ...sidebarProps\n}: AgentWorkspaceLayoutProps) {\n const sessionNav = sessions\n ? (() => {\n const composed = composeSidebarSessions({\n loaderSessions: sessions.sessions,\n optimisticSessions: sessions.optimisticSessions,\n limit: sessions.limit ?? 20,\n totalCount: sessions.totalCount,\n liveUnreadIds: sessions.liveUnreadIds,\n locallyReadIds: sessions.locallyReadIds,\n currentSessionId: sessions.activeSessionId,\n })\n\n return buildSessionNavItem<WorkspaceIcon>({\n id: sessions.id,\n label: sessions.label,\n icon: sessions.icon,\n href: sessions.href,\n sessions: composed.sessions,\n hrefForSession: sessions.hrefForSession,\n activeSessionId: sessions.activeSessionId,\n respondingSessionIds: sessions.respondingSessionIds,\n actions: sessions.actions,\n overflow: composed.hasMore\n ? { href: sessions.href, label: sessions.overflowLabel }\n : undefined,\n emptyLabel: sessions.emptyLabel,\n untitledLabel: sessions.untitledLabel,\n prefetch: sessions.prefetch,\n defaultOpen: sessions.defaultOpen,\n })\n })()\n : undefined\n\n const appNavItems: SidebarLayoutNavItem[] = (apps?.items ?? []).map((app) => {\n const href = apps!.hrefForApp(app.id)\n if (!href.startsWith('/') || href.startsWith('//') || /[?#\\\\]/.test(href)) {\n throw new Error('Workspace app href must be a local route path')\n }\n return {\n id: 'workspace-app:' + app.id,\n label: app.name,\n icon: apps!.icon,\n href,\n prefetch: apps!.prefetch,\n }\n })\n const workspaceNavItems: SidebarLayoutNavItem[] = [\n ...navItems,\n ...appNavItems,\n ...(sessionNav ? [sessionNav] : []),\n ]\n\n const appRoutes: NavRouteDef[] = activeRoute\n ? appNavItems.map((item) => {\n const path = routePathFromHref(item.href!, activeRoute.base)\n if (!path) throw new Error('Workspace app href must be under the active workspace')\n return { id: item.id, path }\n })\n : []\n\n const historyRoutePath = sessions && activeRoute\n ? routePathFromHref(sessions.href, activeRoute.base)\n : null\n\n const resolvedActiveId = activeRoute\n ? resolveActiveNavId({\n ...activeRoute,\n routes: [\n ...activeRoute.routes,\n ...appRoutes,\n ...(sessionNav && historyRoutePath\n ? [{ id: sessions?.id ?? 'history', path: historyRoutePath }]\n : []),\n ],\n })\n : activeId\n\n const layoutProps = {\n hideBelow: 'lg' as const,\n railLabels: true,\n ...sidebarProps,\n }\n\n return (\n <SidebarLayout\n {...layoutProps}\n navItems={workspaceNavItems}\n activeId={resolvedActiveId}\n >\n {children}\n </SidebarLayout>\n )\n}\n"],"mappings":";;;;;;;AAAA,SAAS,qBAAyE;AAwN9E;AAvMJ,SAAS,kBAAkB,MAAc,MAA6B;AACpE,QAAM,OAAO,KAAK,MAAM,QAAQ,CAAC,EAAE,CAAC,KAAK;AACzC,QAAM,OAAO,KAAK,QAAQ,QAAQ,EAAE;AACpC,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,EAAG,QAAO;AACzC,SAAO,KAAK,MAAM,KAAK,MAAM;AAC/B;AAoGO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAA8B;AAC5B,QAAM,aAAa,YACd,MAAM;AACL,UAAM,WAAW,uBAAuB;AAAA,MACtC,gBAAgB,SAAS;AAAA,MACzB,oBAAoB,SAAS;AAAA,MAC7B,OAAO,SAAS,SAAS;AAAA,MACzB,YAAY,SAAS;AAAA,MACrB,eAAe,SAAS;AAAA,MACxB,gBAAgB,SAAS;AAAA,MACzB,kBAAkB,SAAS;AAAA,IAC7B,CAAC;AAED,WAAO,oBAAmC;AAAA,MACxC,IAAI,SAAS;AAAA,MAC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rB,mBAAmB;AAAA,IACjB,GAAG;AAAA,IACH,QAAQ;AAAA,MACN,GAAG,YAAY;AAAA,MACf,GAAG;AAAA,MACH,GAAI,cAAc,mBACd,CAAC,EAAE,IAAI,UAAU,MAAM,WAAW,MAAM,iBAAiB,CAAC,IAC1D,CAAC;AAAA,IACP;AAAA,EACF,CAAC,IACD;AAEJ,QAAM,cAAc;AAAA,IAClB,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,GAAG;AAAA,EACL;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU;AAAA,MACV,UAAU;AAAA,MAET;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.50.
|
|
3
|
+
"version": "0.50.6",
|
|
4
4
|
"packageManager": "pnpm@11.24.0",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -297,6 +297,11 @@
|
|
|
297
297
|
"import": "./dist/chat-react/index.js",
|
|
298
298
|
"default": "./dist/chat-react/index.js"
|
|
299
299
|
},
|
|
300
|
+
"./workspace-apps": {
|
|
301
|
+
"types": "./dist/workspace-apps/index.d.ts",
|
|
302
|
+
"import": "./dist/workspace-apps/index.js",
|
|
303
|
+
"default": "./dist/workspace-apps/index.js"
|
|
304
|
+
},
|
|
300
305
|
"./workspace-react": {
|
|
301
306
|
"types": "./dist/workspace-react/index.d.ts",
|
|
302
307
|
"import": "./dist/workspace-react/index.js",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-identity.ts","../src/stream/turn-observation.ts"],"sourcesContent":["import type { JsonRecord } from './stream-normalizer'\n\n/** Define the structure of a chat message stored for a specific conversation turn */\nexport interface PersistedChatMessageForTurn {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts: Array<Record<string, unknown>> | null\n}\n\n/** Represent a chat turn with resolved user message insertion and prior message context */\nexport interface ResolvedChatTurn {\n turnIndex: number\n shouldInsertUserMessage: boolean\n priorMessages: PersistedChatMessageForTurn[]\n userParts: JsonRecord[]\n /** The id of the user row this turn REUSES (retry dedup), when one was\n * found. Absent on the insert path, where no row exists yet.\n *\n * The reused row is deliberately EXCLUDED from `priorMessages` (it is this\n * turn's own user message, not prior context), so this field is the only\n * way a caller can name it. */\n reusedUserMessageId?: string\n}\n\n/** Normalize and validate a client turn ID string ensuring it meets format and length requirements */\nexport function normalizeClientTurnId(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string') throw new Error('turnId must be a string')\n const trimmed = value.trim()\n if (!trimmed) throw new Error('turnId must not be blank')\n if (trimmed.length > 160) throw new Error('turnId is too long')\n if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {\n throw new Error('turnId contains unsupported characters')\n }\n return trimmed\n}\n\n/** Build an array of text parts with optional turn ID for user input */\nexport function buildUserTextParts(text: string, turnId: string | undefined): JsonRecord[] {\n const part: JsonRecord = { type: 'text', text }\n if (turnId) part.turnId = turnId\n return [part]\n}\n\n/** Resolve whether a message contains any part with the specified turn ID */\nexport function messageHasTurnId(message: PersistedChatMessageForTurn, turnId: string): boolean {\n for (const part of message.parts ?? []) {\n if (part && typeof part === 'object' && String(part.turnId ?? '') === turnId) {\n return true\n }\n }\n return false\n}\n\n/** Resolve a chat turn by determining message reuse and constructing user message parts */\nexport function resolveChatTurn(input: {\n existingMessages: PersistedChatMessageForTurn[]\n userContent: string\n turnId?: string\n /** True when the thread has a turn still RUNNING in the turn-event buffer\n * (`turnStore.listRunning(threadId)`).\n *\n * Without incremental persistence the trailing row of a thread mid-turn is\n * always the user row, so the content fallback below could assume it. With\n * incremental persistence the assistant row lands seconds into the turn, so\n * a retry of that same turn finds an ASSISTANT row trailing and would\n * insert a duplicate user row.\n *\n * This flag is the discriminator that keeps both cases right, and it needs\n * no new state: an assistant row trailing a turn that is still running is\n * that turn's in-flight draft (walk past it — this is a retry), whereas an\n * assistant row trailing a SETTLED turn is a completed answer (stop — the\n * user genuinely repeated a message and deserves a new turn). */\n hasRunningTurn?: boolean\n}): ResolvedChatTurn {\n const { existingMessages, userContent, turnId } = input\n const reusableIndex = findReusableUserMessageIndex(\n existingMessages,\n userContent,\n turnId,\n input.hasRunningTurn === true,\n )\n if (reusableIndex >= 0) {\n // Guarded read: `id` is typed `string`, but these rows come from a product\n // store the shell does not validate, so an adapter that omits it must\n // surface as \"no id\" rather than as the string \"undefined\".\n const reusedId = existingMessages[reusableIndex]?.id\n return {\n turnIndex: countUserMessages(existingMessages.slice(0, reusableIndex)),\n shouldInsertUserMessage: false,\n priorMessages: existingMessages.slice(0, reusableIndex),\n userParts: buildUserTextParts(userContent, turnId),\n ...(typeof reusedId === 'string' && reusedId ? { reusedUserMessageId: reusedId } : {}),\n }\n }\n\n return {\n turnIndex: countUserMessages(existingMessages),\n shouldInsertUserMessage: true,\n priorMessages: existingMessages,\n userParts: buildUserTextParts(userContent, turnId),\n }\n}\n\nfunction findReusableUserMessageIndex(\n messages: PersistedChatMessageForTurn[],\n userContent: string,\n turnId: string | undefined,\n hasRunningTurn: boolean,\n): number {\n if (turnId) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role === 'user' && messageHasTurnId(message, turnId)) return index\n }\n // A caller-supplied id is authoritative. A different id with identical\n // text is a deliberate new turn, while a transport retry reuses the same\n // id and takes the match above. Falling through to content dedup here lets\n // an unrelated abandoned running row swallow an intentional repeat.\n return -1\n }\n\n // Content fallback for a client that sends no turnId. Only the trailing rows\n // of a turn still RUNNING are walked past (they are that turn's incrementally\n // persisted assistant draft); a settled assistant row still ends the scan, so\n // a user who genuinely repeats a message gets a new turn exactly as before.\n let index = messages.length - 1\n if (hasRunningTurn) {\n while (index >= 0 && messages[index]?.role === 'assistant') index -= 1\n }\n const latest = index >= 0 ? messages[index] : undefined\n if (latest?.role === 'user' && latest.content === userContent) return index\n\n return -1\n}\n\nfunction countUserMessages(messages: PersistedChatMessageForTurn[]): number {\n return messages.filter((message) => message.role === 'user').length\n}\n","/** Read-side checkpoints for native chat NDJSON. This never submits or cancels work. */\nexport interface TurnObservation {\n schema: 'turn-observation-v1'\n streamId: string | null\n /** Replay ordinals only. Unsequenced live frames cannot advance this cursor. */\n lastSeq: number\n outcome: 'completed' | 'failed' | null\n replayStatus: string | null\n eventCount: number\n}\n\nexport function parseTurnObservation(value?: unknown): TurnObservation {\n if (value === undefined) return {\n schema: 'turn-observation-v1', streamId: null, lastSeq: 0,\n outcome: null, replayStatus: null, eventCount: 0,\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid turn observation')\n const v = value as Record<string, unknown>\n if (v.schema !== 'turn-observation-v1'\n || !(v.streamId === null || (typeof v.streamId === 'string' && /^[A-Za-z0-9_-]+$/.test(v.streamId)))\n || !Number.isSafeInteger(v.lastSeq) || Number(v.lastSeq) < 0\n || !Number.isSafeInteger(v.eventCount) || Number(v.eventCount) < 0\n || !(v.outcome === null || v.outcome === 'completed' || v.outcome === 'failed')\n || !(v.replayStatus === null || typeof v.replayStatus === 'string')\n || (v.streamId === null && Number(v.lastSeq) > 0)) throw new TypeError('Invalid turn observation')\n return {\n schema: 'turn-observation-v1', streamId: v.streamId as string | null,\n lastSeq: Number(v.lastSeq), outcome: v.outcome as TurnObservation['outcome'],\n replayStatus: v.replayStatus as string | null, eventCount: Number(v.eventCount),\n }\n}\n\nexport interface TurnObservationUpdate {\n checkpoint: TurnObservation\n /** False only for an already-checkpointed replay ordinal. */\n accepted: boolean\n event: Record<string, unknown>\n}\n\n/** Reduce an observed frame. Ordered replay gaps are errors, not silent lost work. */\nexport function observeTurnEvent(previous: TurnObservation, raw: unknown): TurnObservationUpdate {\n const checkpoint = parseTurnObservation(previous)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new TypeError('Turn frame must be an object')\n const outer = raw as Record<string, unknown>\n const inner = outer.kind === 'event' ? outer.event : outer\n if (!inner || typeof inner !== 'object' || Array.isArray(inner)) throw new TypeError('Invalid turn event envelope')\n const event = inner as Record<string, unknown>\n if (typeof event.type !== 'string' || !event.type) throw new TypeError('Turn frame requires a type')\n\n // Even a duplicate marker must not switch which execution we are observing.\n if (event.type === 'turn') {\n if (typeof event.turnId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.turnId)) throw new TypeError('Invalid stream identity')\n if (checkpoint.streamId !== null && checkpoint.streamId !== event.turnId) throw new Error('Replay stream identity changed')\n checkpoint.streamId = event.turnId\n }\n const seq = outer.seq\n if (seq !== undefined && seq !== -1) {\n if (!Number.isSafeInteger(seq) || Number(seq) < 1) throw new TypeError('Invalid replay ordinal')\n if (checkpoint.streamId === null) throw new Error('Replay ordinal arrived before stream identity')\n if (Number(seq) <= checkpoint.lastSeq) return { checkpoint, accepted: false, event }\n if (Number(seq) !== checkpoint.lastSeq + 1) throw new Error('Replay has a gap; retain the checkpoint and inspect durable history')\n checkpoint.lastSeq = Number(seq)\n } else if (seq === -1 && event.type !== 'turn_status') {\n throw new TypeError('Only a turn-status sentinel may have ordinal -1')\n }\n\n if (event.type === 'error' || event.type === 'session.run.failed') checkpoint.outcome = 'failed'\n if (event.type === 'session.run.completed' && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n if (event.type === 'turn_status') {\n if (typeof event.status !== 'string') throw new TypeError('Turn status requires a value')\n checkpoint.replayStatus = event.status\n if (['error', 'failed', 'aborted', 'cancelled'].includes(event.status)) checkpoint.outcome = 'failed'\n if (['complete', 'completed'].includes(event.status) && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n }\n checkpoint.eventCount += 1\n return { checkpoint, accepted: true, event }\n}\n\nexport interface ConsumeTurnStreamOptions {\n checkpoint?: TurnObservation\n /** Commit evidence and its checkpoint durably before acknowledging this frame. */\n commit(update: TurnObservationUpdate): Promise<void>\n /** Bound untrusted frame memory, not total run duration or total transcript size. */\n maxFrameBytes?: number\n}\n\n/**\n * Consume one viewing connection. EOF without a terminal event stays incomplete.\n * A disconnect/abort propagates; the last committed checkpoint remains resumable.\n * The caller owns network observation windows separately from execution deadlines.\n */\nexport async function consumeTurnStream(\n body: AsyncIterable<Uint8Array>,\n options: ConsumeTurnStreamOptions,\n): Promise<TurnObservation> {\n const maxFrameBytes = options.maxFrameBytes ?? 4 * 1024 * 1024\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < 1) throw new RangeError('Frame byte limit must be positive')\n let state = parseTurnObservation(options.checkpoint)\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let pending = ''\n let frameBytes = 0\n async function accept(line: string): Promise<void> {\n if (!line.trim()) return\n const update = observeTurnEvent(state, JSON.parse(line))\n if (update.accepted) await options.commit(update)\n state = update.checkpoint\n }\n for await (const chunk of body) {\n // Count bytes before decoding: a malicious unterminated frame cannot grow\n // without bound, and splitting UTF-8 characters across chunks stays valid.\n let start = 0\n for (let end = 0; end < chunk.length; end += 1) {\n if (chunk[end] !== 10) continue\n frameBytes += end - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start, end + 1), { stream: true })\n await accept(pending)\n pending = ''; frameBytes = 0; start = end + 1\n }\n frameBytes += chunk.length - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start), { stream: true })\n }\n pending += decoder.decode()\n await accept(pending)\n return state\n}\n"],"mappings":";AA0BO,SAAS,sBAAsB,OAAoC;AACxE,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,yBAAyB;AACxE,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,0BAA0B;AACxD,MAAI,QAAQ,SAAS,IA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