@dxos/plugin-script 0.7.5-main.ff8607b → 0.7.5-staging.2ff1350
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/lib/browser/{AutomationPanel-J3SZ5L3Y.mjs → AutomationPanel-6HFRNRWV.mjs} +2 -2
- package/dist/lib/browser/{ScriptContainer-4TSLLF4O.mjs → ScriptContainer-GR7X5NSI.mjs} +96 -68
- package/dist/lib/browser/ScriptContainer-GR7X5NSI.mjs.map +7 -0
- package/dist/lib/browser/artifact-definition-NAWYXFF5.mjs +243 -0
- package/dist/lib/browser/artifact-definition-NAWYXFF5.mjs.map +7 -0
- package/dist/lib/browser/{chunk-45LXDWNF.mjs → chunk-5SXOHNAK.mjs} +3 -3
- package/dist/lib/browser/chunk-5SXOHNAK.mjs.map +7 -0
- package/dist/lib/browser/{chunk-UJD45AFL.mjs → chunk-7RUMC44X.mjs} +18 -6
- package/dist/lib/browser/{chunk-UJD45AFL.mjs.map → chunk-7RUMC44X.mjs.map} +3 -3
- package/dist/lib/browser/chunk-YJAKD6E3.mjs +69 -0
- package/dist/lib/browser/chunk-YJAKD6E3.mjs.map +7 -0
- package/dist/lib/browser/{compiler-K3FNRDDN.mjs → compiler-YY2XSKHQ.mjs} +2 -4
- package/dist/lib/browser/compiler-YY2XSKHQ.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +43 -26
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/{intent-resolver-PPUEEPJJ.mjs → intent-resolver-I6VDXUDH.mjs} +2 -2
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/{react-surface-4CEIM2FE.mjs → react-surface-FGWXHB7P.mjs} +3 -3
- package/dist/lib/browser/{react-surface-4CEIM2FE.mjs.map → react-surface-FGWXHB7P.mjs.map} +2 -2
- package/dist/lib/node/{AutomationPanel-4M55FURO.cjs → AutomationPanel-RBQ4DODN.cjs} +6 -6
- package/dist/lib/node/{ScriptContainer-7JNYGHWK.cjs → ScriptContainer-SLARXOSU.cjs} +91 -61
- package/dist/lib/node/ScriptContainer-SLARXOSU.cjs.map +7 -0
- package/dist/lib/node/artifact-definition-7AANUS3X.cjs +262 -0
- package/dist/lib/node/artifact-definition-7AANUS3X.cjs.map +7 -0
- package/dist/lib/node/chunk-7XULMIYT.cjs +77 -0
- package/dist/lib/node/chunk-7XULMIYT.cjs.map +7 -0
- package/dist/lib/node/{chunk-2LHV7KAI.cjs → chunk-JITODKGN.cjs} +20 -8
- package/dist/lib/node/{chunk-2LHV7KAI.cjs.map → chunk-JITODKGN.cjs.map} +3 -3
- package/dist/lib/node/{chunk-IID7WUQS.cjs → chunk-K3ZZWVXS.cjs} +5 -5
- package/dist/lib/node/chunk-K3ZZWVXS.cjs.map +7 -0
- package/dist/lib/node/{compiler-P2HQB22H.cjs → compiler-UIBLKJKG.cjs} +6 -6
- package/dist/lib/node/compiler-UIBLKJKG.cjs.map +7 -0
- package/dist/lib/node/index.cjs +45 -29
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/{intent-resolver-XZC3OXVT.cjs → intent-resolver-MYATX7IR.cjs} +6 -6
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/{react-surface-I36RLNYL.cjs → react-surface-2GH5HQX4.cjs} +10 -10
- package/dist/lib/node/{react-surface-I36RLNYL.cjs.map → react-surface-2GH5HQX4.cjs.map} +2 -2
- package/dist/lib/node-esm/{AutomationPanel-W6SKG35R.mjs → AutomationPanel-WTVVVMRH.mjs} +2 -2
- package/dist/lib/node-esm/{ScriptContainer-BR6YLHCD.mjs → ScriptContainer-MHRJXMC4.mjs} +96 -68
- package/dist/lib/node-esm/ScriptContainer-MHRJXMC4.mjs.map +7 -0
- package/dist/lib/node-esm/artifact-definition-KBASPVMM.mjs +245 -0
- package/dist/lib/node-esm/artifact-definition-KBASPVMM.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-CGF7EOGD.mjs → chunk-2AFXX34U.mjs} +3 -3
- package/dist/lib/node-esm/chunk-2AFXX34U.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-6CHX4CEL.mjs +71 -0
- package/dist/lib/node-esm/chunk-6CHX4CEL.mjs.map +7 -0
- package/dist/lib/node-esm/{chunk-VZ7NFQL3.mjs → chunk-IAELQPSI.mjs} +18 -6
- package/dist/lib/node-esm/{chunk-VZ7NFQL3.mjs.map → chunk-IAELQPSI.mjs.map} +3 -3
- package/dist/lib/node-esm/{compiler-PDN46H4Y.mjs → compiler-XTXFGZJM.mjs} +2 -4
- package/dist/lib/node-esm/compiler-XTXFGZJM.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +43 -26
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/{intent-resolver-WUVFJ6AO.mjs → intent-resolver-PBDTYC4P.mjs} +2 -2
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/{react-surface-ET5KDADI.mjs → react-surface-MLE3J3TF.mjs} +3 -3
- package/dist/lib/node-esm/{react-surface-ET5KDADI.mjs.map → react-surface-MLE3J3TF.mjs.map} +2 -2
- package/dist/types/src/ScriptPlugin.d.ts.map +1 -1
- package/dist/types/src/capabilities/artifact-definition.d.ts +11 -0
- package/dist/types/src/capabilities/artifact-definition.d.ts.map +1 -0
- package/dist/types/src/capabilities/index.d.ts +1 -0
- package/dist/types/src/capabilities/index.d.ts.map +1 -1
- package/dist/types/src/capabilities/react-surface.d.ts.map +1 -1
- package/dist/types/src/components/AutomationPanel/AutomationPanel.d.ts +1 -2
- package/dist/types/src/components/AutomationPanel/AutomationPanel.d.ts.map +1 -1
- package/dist/types/src/components/DebugPanel/DebugPanel.d.ts +1 -2
- package/dist/types/src/components/DebugPanel/DebugPanel.d.ts.map +1 -1
- package/dist/types/src/components/FrameContainer/FrameContainer.d.ts +3 -4
- package/dist/types/src/components/FrameContainer/FrameContainer.d.ts.map +1 -1
- package/dist/types/src/components/ScriptContainer.d.ts +2 -3
- package/dist/types/src/components/ScriptContainer.d.ts.map +1 -1
- package/dist/types/src/components/ScriptSettings/ScriptSettings.d.ts +1 -2
- package/dist/types/src/components/ScriptSettings/ScriptSettings.d.ts.map +1 -1
- package/dist/types/src/components/ScriptSettingsPanel.d.ts +1 -2
- package/dist/types/src/components/ScriptSettingsPanel.d.ts.map +1 -1
- package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts +2 -3
- package/dist/types/src/components/ScriptToolbar/ScriptToolbar.d.ts.map +1 -1
- package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts +1 -2
- package/dist/types/src/components/TypescriptEditor/TypescriptEditor.d.ts.map +1 -1
- package/dist/types/src/components/index.d.ts +2 -2
- package/dist/types/src/components/index.d.ts.map +1 -1
- package/dist/types/src/events.d.ts +4 -0
- package/dist/types/src/events.d.ts.map +1 -0
- package/dist/types/src/hooks/deploy.d.ts.map +1 -0
- package/dist/types/src/hooks/format.d.ts.map +1 -0
- package/dist/types/src/hooks/index.d.ts +7 -0
- package/dist/types/src/hooks/index.d.ts.map +1 -0
- package/dist/types/src/{components/ScriptToolbar/templateSelect.d.ts → hooks/template.d.ts} +1 -1
- package/dist/types/src/hooks/template.d.ts.map +1 -0
- package/dist/types/src/{components/ScriptToolbar → hooks}/useToolbarAction.d.ts +1 -1
- package/dist/types/src/hooks/useToolbarAction.d.ts.map +1 -0
- package/dist/types/src/hooks/useToolbarState.d.ts.map +1 -0
- package/dist/types/src/hooks/view.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +0 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/templates/chess.d.ts +1 -4
- package/dist/types/src/templates/chess.d.ts.map +1 -1
- package/dist/types/src/templates/discord.d.ts +3 -0
- package/dist/types/src/templates/discord.d.ts.map +1 -0
- package/dist/types/src/templates/echo.d.ts.map +1 -1
- package/dist/types/src/templates/forex-effect.d.ts +3 -0
- package/dist/types/src/templates/forex-effect.d.ts.map +1 -0
- package/dist/types/src/templates/forex.d.ts +1 -4
- package/dist/types/src/templates/forex.d.ts.map +1 -1
- package/dist/types/src/templates/index.d.ts.map +1 -1
- package/dist/types/src/translations.d.ts +6 -0
- package/dist/types/src/translations.d.ts.map +1 -1
- package/package.json +42 -42
- package/src/ScriptPlugin.tsx +28 -12
- package/src/capabilities/artifact-definition.ts +219 -0
- package/src/capabilities/compiler.ts +1 -1
- package/src/capabilities/index.ts +1 -0
- package/src/capabilities/react-surface.tsx +2 -1
- package/src/compiler/compiler.browser.test.ts +1 -1
- package/src/components/DebugPanel/DebugPanel.tsx +2 -2
- package/src/components/FrameContainer/FrameContainer.tsx +5 -4
- package/src/components/ScriptContainer.tsx +10 -5
- package/src/components/ScriptSettingsPanel.tsx +16 -2
- package/src/components/ScriptToolbar/ScriptToolbar.tsx +8 -6
- package/src/components/TypescriptEditor/TypescriptEditor.tsx +2 -2
- package/src/events.ts +11 -0
- package/src/{components/ScriptToolbar → hooks}/deploy.ts +16 -4
- package/src/{components/ScriptToolbar → hooks}/format.ts +1 -1
- package/src/hooks/index.ts +11 -0
- package/src/{components/ScriptToolbar/templateSelect.ts → hooks/template.ts} +2 -2
- package/src/{components/ScriptToolbar → hooks}/useToolbarAction.ts +1 -1
- package/src/{components/ScriptToolbar → hooks}/view.ts +1 -1
- package/src/index.ts +0 -1
- package/src/templates/chess.ts +42 -35
- package/src/templates/discord.ts +103 -0
- package/src/templates/echo.ts +5 -1
- package/src/templates/forex-effect.ts +41 -0
- package/src/templates/forex.ts +23 -16
- package/src/templates/index.ts +15 -0
- package/src/translations.ts +2 -0
- package/dist/lib/browser/ScriptContainer-4TSLLF4O.mjs.map +0 -7
- package/dist/lib/browser/chunk-45LXDWNF.mjs.map +0 -7
- package/dist/lib/browser/chunk-REL2R7SB.mjs +0 -52
- package/dist/lib/browser/chunk-REL2R7SB.mjs.map +0 -7
- package/dist/lib/browser/chunk-SDHKTS6H.mjs +0 -237
- package/dist/lib/browser/chunk-SDHKTS6H.mjs.map +0 -7
- package/dist/lib/browser/compiler-K3FNRDDN.mjs.map +0 -7
- package/dist/lib/node/ScriptContainer-7JNYGHWK.cjs.map +0 -7
- package/dist/lib/node/chunk-IID7WUQS.cjs.map +0 -7
- package/dist/lib/node/chunk-T4TXCRN5.cjs +0 -260
- package/dist/lib/node/chunk-T4TXCRN5.cjs.map +0 -7
- package/dist/lib/node/chunk-TJ4BTPOS.cjs +0 -64
- package/dist/lib/node/chunk-TJ4BTPOS.cjs.map +0 -7
- package/dist/lib/node/compiler-P2HQB22H.cjs.map +0 -7
- package/dist/lib/node-esm/ScriptContainer-BR6YLHCD.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-CGF7EOGD.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-G76M6O46.mjs +0 -239
- package/dist/lib/node-esm/chunk-G76M6O46.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-JJZYWSD7.mjs +0 -54
- package/dist/lib/node-esm/chunk-JJZYWSD7.mjs.map +0 -7
- package/dist/lib/node-esm/compiler-PDN46H4Y.mjs.map +0 -7
- package/dist/types/src/bundler/bundler.d.ts +0 -39
- package/dist/types/src/bundler/bundler.d.ts.map +0 -1
- package/dist/types/src/bundler/bundler.test.d.ts +0 -2
- package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
- package/dist/types/src/bundler/index.d.ts +0 -2
- package/dist/types/src/bundler/index.d.ts.map +0 -1
- package/dist/types/src/components/ScriptToolbar/deploy.d.ts.map +0 -1
- package/dist/types/src/components/ScriptToolbar/format.d.ts.map +0 -1
- package/dist/types/src/components/ScriptToolbar/templateSelect.d.ts.map +0 -1
- package/dist/types/src/components/ScriptToolbar/useToolbarAction.d.ts.map +0 -1
- package/dist/types/src/components/ScriptToolbar/useToolbarState.d.ts.map +0 -1
- package/dist/types/src/components/ScriptToolbar/view.d.ts.map +0 -1
- package/src/bundler/bundler.test.ts +0 -55
- package/src/bundler/bundler.ts +0 -250
- package/src/bundler/index.ts +0 -5
- /package/dist/lib/browser/{AutomationPanel-J3SZ5L3Y.mjs.map → AutomationPanel-6HFRNRWV.mjs.map} +0 -0
- /package/dist/lib/browser/{intent-resolver-PPUEEPJJ.mjs.map → intent-resolver-I6VDXUDH.mjs.map} +0 -0
- /package/dist/lib/node/{AutomationPanel-4M55FURO.cjs.map → AutomationPanel-RBQ4DODN.cjs.map} +0 -0
- /package/dist/lib/node/{intent-resolver-XZC3OXVT.cjs.map → intent-resolver-MYATX7IR.cjs.map} +0 -0
- /package/dist/lib/node-esm/{AutomationPanel-W6SKG35R.mjs.map → AutomationPanel-WTVVVMRH.mjs.map} +0 -0
- /package/dist/lib/node-esm/{intent-resolver-WUVFJ6AO.mjs.map → intent-resolver-PBDTYC4P.mjs.map} +0 -0
- /package/dist/types/src/{components/ScriptToolbar → hooks}/deploy.d.ts +0 -0
- /package/dist/types/src/{components/ScriptToolbar → hooks}/format.d.ts +0 -0
- /package/dist/types/src/{components/ScriptToolbar → hooks}/useToolbarState.d.ts +0 -0
- /package/dist/types/src/{components/ScriptToolbar → hooks}/view.d.ts +0 -0
- /package/src/{components/ScriptToolbar → hooks}/useToolbarState.ts +0 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// packages/plugins/experimental/plugin-script/src/capabilities/artifact-definition.ts
|
|
4
|
+
import { Capabilities, contributes, createIntent } from "@dxos/app-framework";
|
|
5
|
+
import { defineArtifact, defineTool, ToolResult } from "@dxos/artifact";
|
|
6
|
+
import { createArtifactElement } from "@dxos/assistant";
|
|
7
|
+
import { ObjectId, S } from "@dxos/echo-schema";
|
|
8
|
+
import { ScriptType } from "@dxos/functions";
|
|
9
|
+
import { invariant } from "@dxos/invariant";
|
|
10
|
+
import { SpaceAction } from "@dxos/plugin-space/types";
|
|
11
|
+
import { create, makeRef } from "@dxos/react-client/echo";
|
|
12
|
+
import { TextType } from "@dxos/schema";
|
|
13
|
+
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/capabilities/artifact-definition.ts";
|
|
14
|
+
var artifact_definition_default = () => {
|
|
15
|
+
const definition = defineArtifact({
|
|
16
|
+
id: "plugin-script",
|
|
17
|
+
// TODO(dmaretskyi): Since writing scripts requires a lot of domain knowledge,
|
|
18
|
+
// we should offload the work of synthesizing the code to a separate model.
|
|
19
|
+
// The main reasoning model will give it a concrete task and the script model will synthesize the code, knowing all the docs.
|
|
20
|
+
instructions: `
|
|
21
|
+
If the user explicitly requests you to write a script, you can create one.
|
|
22
|
+
If the user requests you to change one of the existing script, you can update it.
|
|
23
|
+
Scripts are short code pieces of executable code that can be used to perform computations, integrate with external systems, and perform automated tasks.
|
|
24
|
+
Each script must follow as strict shape for the definition but the body can contain any valid executable code.
|
|
25
|
+
Scripts are written in JavaScript or TypeScript.
|
|
26
|
+
Each script must define an input schema and output schema.
|
|
27
|
+
Each script must have its own detailed description.
|
|
28
|
+
|
|
29
|
+
Important: You cannot execute scripts. Scripts are only available as tools after the user deploys them. You must only call the available tools.
|
|
30
|
+
|
|
31
|
+
Description:
|
|
32
|
+
The description is a detailed description of the script.
|
|
33
|
+
It is used to describe the script's purpose, input, and output.
|
|
34
|
+
The description is used to generate the script's documentation.
|
|
35
|
+
The description is also goes into the script metadata.
|
|
36
|
+
The description is used by AI to understand the script and its purpose.
|
|
37
|
+
The description must provide cases on when the script should be used.
|
|
38
|
+
|
|
39
|
+
Schema:
|
|
40
|
+
The schema is defined using a schema-DSL library called Effect Schema.
|
|
41
|
+
The input schema describes the arguments that the script accepts.
|
|
42
|
+
The output schema describes the result that the script produces.
|
|
43
|
+
The schema is used to validate the script's input and output.
|
|
44
|
+
The schema is also goes into the script metadata.
|
|
45
|
+
The properties in the schema must have valid descriptions.
|
|
46
|
+
The input and output schemas must both be a struct of fields.
|
|
47
|
+
|
|
48
|
+
Restricts:
|
|
49
|
+
The scripts can only import code from "dxos:functions" module. No other modules are allowed.
|
|
50
|
+
Some web APIs are available - like fetch.
|
|
51
|
+
|
|
52
|
+
Reasoning:
|
|
53
|
+
Before writing a script, synthesize the following information:
|
|
54
|
+
- Description
|
|
55
|
+
- What APIs will be used.
|
|
56
|
+
- Detailed input schema
|
|
57
|
+
- Detailed output schema
|
|
58
|
+
|
|
59
|
+
<apis>
|
|
60
|
+
export function defineFunction(params: {
|
|
61
|
+
description: string,
|
|
62
|
+
inputSchema: S.Schema,
|
|
63
|
+
outputSchema: S.Schema,
|
|
64
|
+
handler: (params: { event: { data: TInput } }) => Promise<TOutput>
|
|
65
|
+
}): FunctionDefinition
|
|
66
|
+
/**
|
|
67
|
+
* Effect Schema
|
|
68
|
+
*/
|
|
69
|
+
export const S;
|
|
70
|
+
|
|
71
|
+
// Examples:
|
|
72
|
+
|
|
73
|
+
S.String
|
|
74
|
+
S.Number
|
|
75
|
+
S.Boolean
|
|
76
|
+
S.Struct({
|
|
77
|
+
from: S.String.annotations({ description: 'The source currency' }),
|
|
78
|
+
to: S.String.annotations({ description: 'The target currency' }),
|
|
79
|
+
})
|
|
80
|
+
S.Array(S.String)
|
|
81
|
+
S.Union(S.String, S.Number)
|
|
82
|
+
S.optional(S.String)
|
|
83
|
+
S.String.annotations({ description: 'The source currency' })
|
|
84
|
+
</apis>
|
|
85
|
+
|
|
86
|
+
<handler_function>
|
|
87
|
+
Async function that takes the argument in the form of:
|
|
88
|
+
|
|
89
|
+
type HandlerFunctionParam = {
|
|
90
|
+
event: {
|
|
91
|
+
data: T // The input schema
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
The function must return the result that matches the output schema.
|
|
96
|
+
</handler_function>
|
|
97
|
+
|
|
98
|
+
<example>
|
|
99
|
+
import { defineFunction, S } from 'dxos:functions';
|
|
100
|
+
|
|
101
|
+
export default defineFunction({
|
|
102
|
+
description: 'Returns the exchange rate between two currencies.',
|
|
103
|
+
|
|
104
|
+
inputSchema: S.Struct({
|
|
105
|
+
from: S.String.annotations({ description: 'The source currency' }),
|
|
106
|
+
to: S.String.annotations({ description: 'The target currency' }),
|
|
107
|
+
}),
|
|
108
|
+
|
|
109
|
+
outputSchema: S.Struct({
|
|
110
|
+
rate: S.String.annotations({ description: 'The exchange rate' }),
|
|
111
|
+
}),
|
|
112
|
+
|
|
113
|
+
handler: async ({
|
|
114
|
+
event: {
|
|
115
|
+
data: { from, to },
|
|
116
|
+
},
|
|
117
|
+
}: any) => {
|
|
118
|
+
const res = await fetch(\`https://free.ratesdb.com/v1/rates?from=\${from}&to=\${to}\`);
|
|
119
|
+
const {
|
|
120
|
+
data: { rates },
|
|
121
|
+
} = await res.json();
|
|
122
|
+
|
|
123
|
+
return { rate: rates[to].toString() };
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
</example>
|
|
127
|
+
`,
|
|
128
|
+
schema: ScriptType,
|
|
129
|
+
tools: [
|
|
130
|
+
defineTool({
|
|
131
|
+
name: "script_new",
|
|
132
|
+
description: "Create a new script. Returns the artifact definition for the script",
|
|
133
|
+
schema: S.Struct({
|
|
134
|
+
name: S.String.annotations({
|
|
135
|
+
description: "The name of the script"
|
|
136
|
+
}),
|
|
137
|
+
code: S.String.annotations({
|
|
138
|
+
description: "The full code of the script in JavaScript or TypeScript. Must be valid executable code."
|
|
139
|
+
})
|
|
140
|
+
}),
|
|
141
|
+
execute: async ({ name, code }, { extensions }) => {
|
|
142
|
+
invariant(extensions?.space, "No space", {
|
|
143
|
+
F: __dxlog_file,
|
|
144
|
+
L: 149,
|
|
145
|
+
S: void 0,
|
|
146
|
+
A: [
|
|
147
|
+
"extensions?.space",
|
|
148
|
+
"'No space'"
|
|
149
|
+
]
|
|
150
|
+
});
|
|
151
|
+
invariant(extensions?.dispatch, "No intent dispatcher", {
|
|
152
|
+
F: __dxlog_file,
|
|
153
|
+
L: 150,
|
|
154
|
+
S: void 0,
|
|
155
|
+
A: [
|
|
156
|
+
"extensions?.dispatch",
|
|
157
|
+
"'No intent dispatcher'"
|
|
158
|
+
]
|
|
159
|
+
});
|
|
160
|
+
const script = create(ScriptType, {
|
|
161
|
+
name,
|
|
162
|
+
source: makeRef(create(TextType, {
|
|
163
|
+
content: code
|
|
164
|
+
}))
|
|
165
|
+
});
|
|
166
|
+
extensions.space.db.add(script);
|
|
167
|
+
await extensions.space.db.flush();
|
|
168
|
+
const intent = createIntent(SpaceAction.AddObject, {
|
|
169
|
+
target: extensions.space,
|
|
170
|
+
object: script
|
|
171
|
+
});
|
|
172
|
+
const { data, error } = await extensions.dispatch(intent);
|
|
173
|
+
if (!data || error) {
|
|
174
|
+
return ToolResult.Error(error?.message ?? "Failed to create chess game");
|
|
175
|
+
}
|
|
176
|
+
return ToolResult.Success(createArtifactElement(script.id));
|
|
177
|
+
}
|
|
178
|
+
}),
|
|
179
|
+
defineTool({
|
|
180
|
+
name: "script_inspect",
|
|
181
|
+
description: "Inspect a script. Returns the artifact definition for the script",
|
|
182
|
+
schema: S.Struct({
|
|
183
|
+
id: ObjectId
|
|
184
|
+
}),
|
|
185
|
+
execute: async ({ id }, { extensions }) => {
|
|
186
|
+
invariant(extensions?.space, "No space", {
|
|
187
|
+
F: __dxlog_file,
|
|
188
|
+
L: 178,
|
|
189
|
+
S: void 0,
|
|
190
|
+
A: [
|
|
191
|
+
"extensions?.space",
|
|
192
|
+
"'No space'"
|
|
193
|
+
]
|
|
194
|
+
});
|
|
195
|
+
const script = await extensions.space.db.query({
|
|
196
|
+
id
|
|
197
|
+
}).first();
|
|
198
|
+
const { content } = await script.source.load();
|
|
199
|
+
return ToolResult.Success({
|
|
200
|
+
name: script.name,
|
|
201
|
+
code: content
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}),
|
|
205
|
+
defineTool({
|
|
206
|
+
name: "script_update",
|
|
207
|
+
description: "Update a script. Returns the artifact definition for the script",
|
|
208
|
+
schema: S.Struct({
|
|
209
|
+
id: ObjectId,
|
|
210
|
+
code: S.String.annotations({
|
|
211
|
+
description: "The full code of the script in JavaScript or TypeScript. Must be valid executable code."
|
|
212
|
+
})
|
|
213
|
+
}),
|
|
214
|
+
execute: async ({ id, code }, { extensions }) => {
|
|
215
|
+
invariant(extensions?.space, "No space", {
|
|
216
|
+
F: __dxlog_file,
|
|
217
|
+
L: 199,
|
|
218
|
+
S: void 0,
|
|
219
|
+
A: [
|
|
220
|
+
"extensions?.space",
|
|
221
|
+
"'No space'"
|
|
222
|
+
]
|
|
223
|
+
});
|
|
224
|
+
const script = await extensions.space.db.query({
|
|
225
|
+
id
|
|
226
|
+
}).first();
|
|
227
|
+
const source = await script.source.load();
|
|
228
|
+
if (!source) {
|
|
229
|
+
return ToolResult.Error("Script not found");
|
|
230
|
+
}
|
|
231
|
+
source.content = code;
|
|
232
|
+
await extensions.space?.db.flush();
|
|
233
|
+
return ToolResult.Success({
|
|
234
|
+
name: script.name
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
})
|
|
238
|
+
]
|
|
239
|
+
});
|
|
240
|
+
return contributes(Capabilities.ArtifactDefinition, definition);
|
|
241
|
+
};
|
|
242
|
+
export {
|
|
243
|
+
artifact_definition_default as default
|
|
244
|
+
};
|
|
245
|
+
//# sourceMappingURL=artifact-definition-KBASPVMM.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/capabilities/artifact-definition.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Capabilities, contributes, createIntent, type PromiseIntentDispatcher } from '@dxos/app-framework';\nimport { defineArtifact, defineTool, ToolResult } from '@dxos/artifact';\nimport { createArtifactElement } from '@dxos/assistant';\nimport { ObjectId, S } from '@dxos/echo-schema';\nimport { ScriptType } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceAction } from '@dxos/plugin-space/types';\nimport { create, makeRef, type Space } from '@dxos/react-client/echo';\nimport { TextType } from '@dxos/schema';\n\n// TODO(burdon): Factor out.\ndeclare global {\n interface ToolContextExtensions {\n space?: Space;\n dispatch?: PromiseIntentDispatcher;\n }\n}\n\nexport default () => {\n const definition = defineArtifact({\n id: 'plugin-script',\n // TODO(dmaretskyi): Since writing scripts requires a lot of domain knowledge,\n // we should offload the work of synthesizing the code to a separate model.\n // The main reasoning model will give it a concrete task and the script model will synthesize the code, knowing all the docs.\n instructions: `\n If the user explicitly requests you to write a script, you can create one.\n If the user requests you to change one of the existing script, you can update it.\n Scripts are short code pieces of executable code that can be used to perform computations, integrate with external systems, and perform automated tasks.\n Each script must follow as strict shape for the definition but the body can contain any valid executable code.\n Scripts are written in JavaScript or TypeScript.\n Each script must define an input schema and output schema.\n Each script must have its own detailed description.\n\n Important: You cannot execute scripts. Scripts are only available as tools after the user deploys them. You must only call the available tools.\n\n Description:\n The description is a detailed description of the script.\n It is used to describe the script's purpose, input, and output.\n The description is used to generate the script's documentation.\n The description is also goes into the script metadata.\n The description is used by AI to understand the script and its purpose.\n The description must provide cases on when the script should be used.\n\n Schema: \n The schema is defined using a schema-DSL library called Effect Schema.\n The input schema describes the arguments that the script accepts.\n The output schema describes the result that the script produces.\n The schema is used to validate the script's input and output.\n The schema is also goes into the script metadata.\n The properties in the schema must have valid descriptions.\n The input and output schemas must both be a struct of fields.\n\n Restricts:\n The scripts can only import code from \"dxos:functions\" module. No other modules are allowed.\n Some web APIs are available - like fetch.\n\n Reasoning:\n Before writing a script, synthesize the following information:\n - Description\n - What APIs will be used.\n - Detailed input schema\n - Detailed output schema\n\n <apis>\n export function defineFunction(params: { \n description: string, \n inputSchema: S.Schema, \n outputSchema: S.Schema, \n handler: (params: { event: { data: TInput } }) => Promise<TOutput> \n }): FunctionDefinition\n /**\n * Effect Schema\n */\n export const S; \n\n // Examples: \n\n S.String\n S.Number\n S.Boolean\n S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n })\n S.Array(S.String)\n S.Union(S.String, S.Number)\n S.optional(S.String)\n S.String.annotations({ description: 'The source currency' })\n </apis>\n\n <handler_function>\n Async function that takes the argument in the form of:\n\n type HandlerFunctionParam = {\n event: {\n data: T // The input schema\n },\n }\n\n The function must return the result that matches the output schema.\n </handler_function>\n \n <example>\n import { defineFunction, S } from 'dxos:functions';\n\n export default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.Struct({\n rate: S.String.annotations({ description: 'The exchange rate' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\n const res = await fetch(\\`https://free.ratesdb.com/v1/rates?from=\\${from}&to=\\${to}\\`);\n const {\n data: { rates },\n } = await res.json();\n\n return { rate: rates[to].toString() };\n },\n });\n </example>\n `,\n schema: ScriptType,\n tools: [\n defineTool({\n name: 'script_new',\n description: 'Create a new script. Returns the artifact definition for the script',\n schema: S.Struct({\n name: S.String.annotations({ description: 'The name of the script' }),\n code: S.String.annotations({\n description: 'The full code of the script in JavaScript or TypeScript. Must be valid executable code.',\n }),\n }),\n execute: async ({ name, code }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n invariant(extensions?.dispatch, 'No intent dispatcher');\n const script = create(ScriptType, {\n name,\n source: makeRef(\n create(TextType, {\n content: code,\n }),\n ),\n });\n extensions.space.db.add(script);\n await extensions.space.db.flush();\n\n const intent = createIntent(SpaceAction.AddObject, { target: extensions.space, object: script });\n const { data, error } = await extensions.dispatch(intent);\n if (!data || error) {\n return ToolResult.Error(error?.message ?? 'Failed to create chess game');\n }\n\n return ToolResult.Success(createArtifactElement(script.id));\n },\n }),\n defineTool({\n name: 'script_inspect',\n description: 'Inspect a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\n }),\n execute: async ({ id }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n\n const script = (await extensions.space.db.query({ id }).first()) as ScriptType;\n const { content } = await script.source.load();\n\n return ToolResult.Success({\n name: script.name,\n code: content,\n });\n },\n }),\n defineTool({\n name: 'script_update',\n description: 'Update a script. Returns the artifact definition for the script',\n schema: S.Struct({\n id: ObjectId,\n code: S.String.annotations({\n description: 'The full code of the script in JavaScript or TypeScript. Must be valid executable code.',\n }),\n }),\n execute: async ({ id, code }, { extensions }) => {\n invariant(extensions?.space, 'No space');\n\n const script = (await extensions.space.db.query({ id }).first()) as ScriptType;\n const source = await script.source.load();\n if (!source) {\n return ToolResult.Error('Script not found');\n }\n\n source.content = code;\n await extensions.space?.db.flush();\n\n return ToolResult.Success({\n name: script.name,\n });\n },\n }),\n ],\n });\n\n return contributes(Capabilities.ArtifactDefinition, definition);\n};\n"],
|
|
5
|
+
"mappings": ";;;AAIA,SAASA,cAAcC,aAAaC,oBAAkD;AACtF,SAASC,gBAAgBC,YAAYC,kBAAkB;AACvD,SAASC,6BAA6B;AACtC,SAASC,UAAUC,SAAS;AAC5B,SAASC,kBAAkB;AAC3B,SAASC,iBAAiB;AAC1B,SAASC,mBAAmB;AAC5B,SAASC,QAAQC,eAA2B;AAC5C,SAASC,gBAAgB;;AAUzB,IAAA,8BAAe,MAAA;AACb,QAAMC,aAAaZ,eAAe;IAChCa,IAAI;;;;IAIJC,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4GdC,QAAQT;IACRU,OAAO;MACLf,WAAW;QACTgB,MAAM;QACNC,aAAa;QACbH,QAAQV,EAAEc,OAAO;UACfF,MAAMZ,EAAEe,OAAOC,YAAY;YAAEH,aAAa;UAAyB,CAAA;UACnEI,MAAMjB,EAAEe,OAAOC,YAAY;YACzBH,aAAa;UACf,CAAA;QACF,CAAA;QACAK,SAAS,OAAO,EAAEN,MAAMK,KAAI,GAAI,EAAEE,WAAU,MAAE;AAC5CjB,oBAAUiB,YAAYC,OAAO,YAAA;;;;;;;;;AAC7BlB,oBAAUiB,YAAYE,UA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AAYC,OAAO,YAAA;;;;;;;;;AAE7B,gBAAME,SAAU,MAAMH,WAAWC,MAAMK,GAAGY,MAAM;YAAE7B;UAAG,CAAA,EAAG8B,MAAK;AAC7D,gBAAMf,SAAS,MAAMD,OAAOC,OAAOgB,KAAI;AACvC,cAAI,CAAChB,QAAQ;AACX,mBAAO1B,WAAWqC,MAAM,kBAAA;UAC1B;AAEAX,iBAAOC,UAAUP;AACjB,gBAAME,WAAWC,OAAOK,GAAGE,MAAAA;AAE3B,iBAAO9B,WAAWuC,QAAQ;YACxBxB,MAAMU,OAAOV;UACf,CAAA;QACF;MACF,CAAA;;EAEJ,CAAA;AAEA,SAAOnB,YAAYD,aAAagD,oBAAoBjC,UAAAA;AACtD;",
|
|
6
|
+
"names": ["Capabilities", "contributes", "createIntent", "defineArtifact", "defineTool", "ToolResult", "createArtifactElement", "ObjectId", "S", "ScriptType", "invariant", "SpaceAction", "create", "makeRef", "TextType", "definition", "id", "instructions", "schema", "tools", "name", "description", "Struct", "String", "annotations", "code", "execute", "extensions", "space", "dispatch", "script", "source", "content", "db", "add", "flush", "intent", "AddObject", "target", "object", "data", "error", "Error", "message", "Success", "query", "first", "load", "ArtifactDefinition"]
|
|
7
|
+
}
|
|
@@ -8,7 +8,7 @@ import React, { forwardRef, useEffect, useRef, useState } from "react";
|
|
|
8
8
|
import { log } from "@dxos/log";
|
|
9
9
|
import { Avatar, Icon, Input, Toolbar, useTranslation } from "@dxos/react-ui";
|
|
10
10
|
import { SyntaxHighlighter } from "@dxos/react-ui-syntax-highlighter";
|
|
11
|
-
import { mx } from "@dxos/react-ui-theme";
|
|
11
|
+
import { errorText, mx } from "@dxos/react-ui-theme";
|
|
12
12
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/components/DebugPanel/DebugPanel.tsx";
|
|
13
13
|
var DebugPanel = ({ classNames, functionUrl }) => {
|
|
14
14
|
const { t } = useTranslation(SCRIPT_PLUGIN);
|
|
@@ -220,7 +220,7 @@ var MessageItem = ({ classNames, message }) => {
|
|
|
220
220
|
return /* @__PURE__ */ React.createElement("div", {
|
|
221
221
|
className: mx("flex", type === "request" ? "ml-[1rem] justify-end" : "mr-[1rem]", classNames)
|
|
222
222
|
}, error && /* @__PURE__ */ React.createElement("div", {
|
|
223
|
-
className: mx(wrapper, "whitespace-pre
|
|
223
|
+
className: mx(wrapper, "whitespace-pre", errorText)
|
|
224
224
|
}, String(error)), text !== void 0 && /* @__PURE__ */ React.createElement("div", {
|
|
225
225
|
className: mx(wrapper, type === "request" && "bg-primary-400 dark:bg-primary-600")
|
|
226
226
|
}, text || "\xD8"), data && /* @__PURE__ */ React.createElement(SyntaxHighlighter, {
|
|
@@ -238,4 +238,4 @@ var RobotAvatar = () => /* @__PURE__ */ React.createElement(Avatar.Root, {
|
|
|
238
238
|
export {
|
|
239
239
|
DebugPanel
|
|
240
240
|
};
|
|
241
|
-
//# sourceMappingURL=chunk-
|
|
241
|
+
//# sourceMappingURL=chunk-2AFXX34U.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/components/DebugPanel/DebugPanel.tsx"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport React, { forwardRef, useEffect, useRef, useState } from 'react';\n\nimport { log } from '@dxos/log';\nimport { Avatar, Icon, Input, type ThemedClassName, Toolbar, useTranslation } from '@dxos/react-ui';\nimport { SyntaxHighlighter } from '@dxos/react-ui-syntax-highlighter';\nimport { errorText, mx } from '@dxos/react-ui-theme';\n\nimport { SCRIPT_PLUGIN } from '../../meta';\n\ntype State = 'pending' | 'responding';\n\n/**\n * Request or response.\n */\ntype Message = { type: 'request' | 'response'; text?: string; data?: any; error?: Error };\n\nexport type DebugPanelProps = ThemedClassName<{\n functionUrl?: string;\n}>;\n\nexport const DebugPanel = ({ classNames, functionUrl }: DebugPanelProps) => {\n const { t } = useTranslation(SCRIPT_PLUGIN);\n\n const inputRef = useRef<HTMLInputElement>(null);\n const [input, setInput] = useState('');\n const [result, setResult] = useState('');\n const [state, setState] = useState<State | null>(null);\n\n // TODO(burdon): Persistent history -- at least for session (non-space ECHO data?)\n const [history, setHistory] = useState<Message[]>([]);\n\n const scrollerRef = useRef<HTMLDivElement>(null);\n const handleScroll = () => {\n if (scrollerRef.current) {\n scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;\n }\n };\n\n const controller = useRef<AbortController>();\n useEffect(() => {\n return () => {\n handleStop();\n };\n }, []);\n\n const handleStop = () => {\n controller.current?.abort('stop');\n controller.current = undefined;\n };\n\n const handleClear = () => {\n handleStop();\n setInput('');\n setResult('');\n setHistory([]);\n inputRef.current?.focus();\n };\n\n const handleResponse = ({ text, data, error }: { text?: string; data?: any; error?: Error } = {}) => {\n controller.current = undefined;\n setHistory((history) => [...history, { type: 'response', text, data, error } satisfies Message]);\n setResult('');\n setState(null);\n handleScroll();\n };\n\n const handleRequest = async (input: string) => {\n // Returns a promise that resolves when a value has been received.\n try {\n setState('pending');\n\n let data = null;\n // Detect JSON input.\n if (input.charAt(0) === '{') {\n try {\n const validJsonString = input.replace(/'/g, '\"').replace(/([{,]\\s*)([a-zA-Z0-9_]+)(\\s*:)/g, '$1\"$2\"$3');\n data = JSON.parse(validJsonString);\n input = JSON.stringify(data, null, 2);\n } catch (err) {\n inputRef.current?.focus();\n return;\n }\n }\n\n setInput('');\n setResult('');\n setHistory((history) => [...history, { type: 'request', text: input }]);\n setTimeout(() => {\n handleScroll();\n });\n\n // Throws DOMException when aborted.\n controller.current = new AbortController();\n const response = await fetch(functionUrl!, {\n signal: controller.current.signal,\n method: 'POST',\n body: input,\n headers: {\n 'Content-Type': data ? 'application/json' : 'text/plain',\n },\n });\n\n // Check for error.\n if (!response.ok) {\n const text = await response.text();\n handleResponse({ error: new Error(text || response.statusText || String(response.status)) });\n return;\n }\n\n // Check for JSON.\n const contentType = response.headers.get('content-type');\n if (contentType === 'application/json') {\n const data = await response.json();\n handleResponse({ data });\n return;\n }\n\n // Text (including streaming).\n setState('responding');\n let text = '';\n const reader = response.body!.getReader();\n const pump = async ({ done, value }: ReadableStreamReadResult<Uint8Array>): Promise<void> => {\n text = text + new TextDecoder().decode(value);\n if (!controller.current || done) {\n handleResponse({ text });\n return;\n }\n\n setResult(text);\n setTimeout(() => {\n handleScroll();\n });\n\n return reader.read().then(pump);\n };\n\n void reader\n .read()\n .then(pump)\n .catch((err) => {\n if (err.name !== 'AbortError') {\n log.catch(err);\n }\n });\n } catch (err: any) {\n if (err !== 'stop') {\n const error = err instanceof Error ? err : new Error(err);\n handleResponse({ error });\n log.catch(err);\n } else {\n handleResponse();\n }\n }\n };\n\n return (\n <div className={mx('flex flex-col h-full overflow-hidden', classNames)}>\n {/* TODO(burdon): Replace with Thread. */}\n <MessageThread ref={scrollerRef} state={state} result={result} history={history} />\n\n <Toolbar.Root classNames='p-1'>\n <Input.Root>\n <Input.TextInput\n ref={inputRef}\n autoFocus\n placeholder={t('function request placeholder')}\n value={input}\n onChange={(ev) => setInput(ev.target.value)}\n onKeyDown={(ev) => ev.key === 'Enter' && handleRequest(input)}\n />\n </Input.Root>\n <Toolbar.Button onClick={() => handleRequest(input)}>\n <Icon icon='ph--play--regular' size={4} />\n </Toolbar.Button>\n <Toolbar.Button onClick={() => (state ? handleStop() : handleClear())}>\n <Icon icon={state ? 'ph--stop--regular' : 'ph--trash--regular'} size={4} />\n </Toolbar.Button>\n </Toolbar.Root>\n </div>\n );\n};\n\n// TODO(burdon): Replace with thread?\n// TODO(burdon): Button to delete individual messages.\n// TODO(burdon): Button to edit/re-run question.\ntype MessageThreadProps = {\n state: State | null;\n history: Message[];\n result: string;\n};\n\nconst MessageThread = forwardRef<HTMLDivElement, MessageThreadProps>(\n ({ state, history, result }: MessageThreadProps, forwardedRef) => {\n if (!history.length && !result.length) {\n return null;\n }\n\n return (\n <div ref={forwardedRef} className='flex flex-col gap-6 h-full p-2 overflow-x-hidden overflow-y-auto'>\n {history.map((message, i) => (\n <div key={i} className='grid grid-cols-[2rem_1fr_2rem]'>\n <div className='p-1'>{message.type === 'response' && <RobotAvatar />}</div>\n <div className='overflow-auto'>\n <MessageItem message={message} />\n </div>\n </div>\n ))}\n\n {result?.length > 0 && (\n <div className='grid grid-cols-[2rem_1fr_2rem]'>\n <div className='p-1'>\n {(state === 'pending' && <Icon icon='ph--spinner--regular' size={6} classNames='animate-spin' />) || (\n <Icon icon='ph--robot--regular' size={6} classNames='animate-[pulse_1s_ease-in-out_infinite]' />\n )}\n </div>\n <div className='overflow-auto'>\n <MessageItem message={{ type: 'response', text: result }} />\n </div>\n </div>\n )}\n </div>\n );\n },\n);\n\nconst MessageItem = ({ classNames, message }: ThemedClassName<{ message: Message }>) => {\n const { type, text, data, error } = message;\n const wrapper = 'p-1 px-2 rounded-lg bg-hoverSurface overflow-auto';\n return (\n <div className={mx('flex', type === 'request' ? 'ml-[1rem] justify-end' : 'mr-[1rem]', classNames)}>\n {error && <div className={mx(wrapper, 'whitespace-pre', errorText)}>{String(error)}</div>}\n\n {text !== undefined && (\n <div className={mx(wrapper, type === 'request' && 'bg-primary-400 dark:bg-primary-600')}>\n {text || '\\u00D8'}\n </div>\n )}\n\n {data && (\n <SyntaxHighlighter language='json' className={mx(wrapper, 'px-8 py-2 text-xs')}>\n {JSON.stringify(data, null, 2)}\n </SyntaxHighlighter>\n )}\n </div>\n );\n};\n\nconst RobotAvatar = () => (\n <Avatar.Root size={6} variant='circle'>\n <Avatar.Frame>\n <Avatar.Icon icon='ph--robot--regular' />\n </Avatar.Frame>\n </Avatar.Root>\n);\n"],
|
|
5
|
+
"mappings": ";;;;;;AAIA,OAAOA,SAASC,YAAYC,WAAWC,QAAQC,gBAAgB;AAE/D,SAASC,WAAW;AACpB,SAASC,QAAQC,MAAMC,OAA6BC,SAASC,sBAAsB;AACnF,SAASC,yBAAyB;AAClC,SAASC,WAAWC,UAAU;;AAevB,IAAMC,aAAa,CAAC,EAAEC,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A,GAE3EF,SAASJ,UACR,sBAAA,cAAC4C,OAAAA;IAAIC,WAAWC,GAAG2B,SAASlE,SAAS,aAAa,oCAAA;KAC/CH,QAAQ,MAAA,GAIZC,QACC,sBAAA,cAACsE,mBAAAA;IAAkBC,UAAS;IAAO/B,WAAWC,GAAG2B,SAAS,mBAAA;KACvD7D,KAAKE,UAAUT,MAAM,MAAM,CAAA,CAAA,CAAA;AAKtC;AAEA,IAAMkE,cAAc,MAClB,sBAAA,cAACM,OAAO3B,MAAI;EAACc,MAAM;EAAGc,SAAQ;GAC5B,sBAAA,cAACD,OAAOE,OAAK,MACX,sBAAA,cAACF,OAAOf,MAAI;EAACC,MAAK;;",
|
|
6
|
+
"names": ["React", "forwardRef", "useEffect", "useRef", "useState", "log", "Avatar", "Icon", "Input", "Toolbar", "useTranslation", "SyntaxHighlighter", "errorText", "mx", "DebugPanel", "classNames", "functionUrl", "t", "useTranslation", "SCRIPT_PLUGIN", "inputRef", "useRef", "input", "setInput", "useState", "result", "setResult", "state", "setState", "history", "setHistory", "scrollerRef", "handleScroll", "current", "scrollTop", "scrollHeight", "controller", "useEffect", "handleStop", "abort", "undefined", "handleClear", "focus", "handleResponse", "text", "data", "error", "type", "handleRequest", "charAt", "validJsonString", "replace", "JSON", "parse", "stringify", "err", "setTimeout", "AbortController", "response", "fetch", "signal", "method", "body", "headers", "ok", "Error", "statusText", "String", "status", "contentType", "get", "json", "reader", "getReader", "pump", "done", "value", "TextDecoder", "decode", "read", "then", "catch", "name", "log", "div", "className", "mx", "MessageThread", "ref", "Toolbar", "Root", "Input", "TextInput", "autoFocus", "placeholder", "onChange", "ev", "target", "onKeyDown", "key", "Button", "onClick", "Icon", "icon", "size", "forwardRef", "forwardedRef", "length", "map", "message", "i", "RobotAvatar", "MessageItem", "wrapper", "errorText", "SyntaxHighlighter", "language", "Avatar", "variant", "Frame"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// raw-loader:./chat.ts?raw
|
|
4
|
+
var chat_default = "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${textBody}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === ChainInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === ChainInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === ChainInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum ChainInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n";
|
|
5
|
+
|
|
6
|
+
// raw-loader:./chess.ts?raw
|
|
7
|
+
var chess_default = "// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({\n event: {\n data: { changedObjectId, player = 'b' },\n },\n context: { space },\n }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n";
|
|
8
|
+
|
|
9
|
+
// raw-loader:./discord.ts?raw
|
|
10
|
+
var discord_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { createStatic, EchoObject, defineFunction, DXN, Filter, ObjectId, S } from 'dxos:functions';\nimport {\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { DiscordConfig, DiscordREST, DiscordRESTMemoryLive } from 'https://esm.sh/dfx@0.113.0?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.13.3';\n\nconst MessageSchema = S.Struct({\n id: S.String,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(EchoObject('example.com/type/Message', '0.1.0'));\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise(() =>\n space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n );\n const { objects } = yield* Effect.tryPromise(() => space.queues.queryQueue(DXN.parse(queueId)));\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n createStatic(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise(() => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages));\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n";
|
|
11
|
+
|
|
12
|
+
// raw-loader:./echo.ts?raw
|
|
13
|
+
var echo_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n";
|
|
14
|
+
|
|
15
|
+
// raw-loader:./email.ts?raw
|
|
16
|
+
var email_default = "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const { data, trigger } = (await request.json()) as RequestPayload;\n\n const documentId = trigger.meta.targetDocumentId;\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${data.from}`,\n `**Subject:** ${data.subject}`,\n `**Date:** ${data.created}`,\n '',\n data.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n data: { from: string; subject: string; created: string; body: string };\n trigger: { meta: { targetDocumentId: string } };\n};\n";
|
|
17
|
+
|
|
18
|
+
// raw-loader:./forex-effect.ts?raw
|
|
19
|
+
var forex_effect_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.13.3';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n";
|
|
20
|
+
|
|
21
|
+
// raw-loader:./forex.ts?raw
|
|
22
|
+
var forex_default = "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return rates[to].toString();\n },\n});\n";
|
|
23
|
+
|
|
24
|
+
// packages/plugins/experimental/plugin-script/src/templates/index.ts
|
|
25
|
+
var removeHeader = (str) => str.split("\n").slice(4).join("\n");
|
|
26
|
+
var templates = [
|
|
27
|
+
{
|
|
28
|
+
id: "dxos.org/script/echo",
|
|
29
|
+
name: "Echo",
|
|
30
|
+
source: removeHeader(echo_default)
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
id: "dxos.org/script/forex",
|
|
34
|
+
name: "Forex",
|
|
35
|
+
source: removeHeader(forex_default)
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
id: "dxos.org/script/forex-effect",
|
|
39
|
+
name: "Forex (Effect)",
|
|
40
|
+
source: removeHeader(forex_effect_default)
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: "dxos.org/script/gpt",
|
|
44
|
+
name: "Gpt",
|
|
45
|
+
source: removeHeader(chat_default),
|
|
46
|
+
presetId: "dxos.org/function/gpt"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: "dxos.org/script/chess",
|
|
50
|
+
name: "Chess",
|
|
51
|
+
source: removeHeader(chess_default),
|
|
52
|
+
presetId: "dxos.org/function/chess"
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
id: "dxos.org/script/email",
|
|
56
|
+
name: "Email",
|
|
57
|
+
source: removeHeader(email_default),
|
|
58
|
+
presetId: "dxos.org/function/email"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: "dxos.org/script/discord",
|
|
62
|
+
name: "Discord",
|
|
63
|
+
source: removeHeader(discord_default),
|
|
64
|
+
presetId: "dxos.org/function/discord"
|
|
65
|
+
}
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
export {
|
|
69
|
+
templates
|
|
70
|
+
};
|
|
71
|
+
//# sourceMappingURL=chunk-6CHX4CEL.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["raw-loader:./chat.ts?raw", "raw-loader:./chess.ts?raw", "raw-loader:./discord.ts?raw", "raw-loader:./echo.ts?raw", "raw-loader:./email.ts?raw", "raw-loader:./forex-effect.ts?raw", "raw-loader:./forex.ts?raw", "../../../src/templates/index.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport { transformServerSentEvents } from 'https://esm.sh/@dxos/script-toolbox';\n\n/**\n * Chatbot that answers questions based on the context data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space, ai },\n}: any) => {\n const textBody = await request.text();\n let parsedRequest: any;\n try {\n parsedRequest = JSON.parse(textBody);\n } catch (err) {\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: true,\n prompt: `\n Using only the context data below to answer the user's question.\n If you cannot answer the question from the provided content, then reply with \"I don't know.\"\n\n CONTEXT:\n ${await getContext({ space })}\n\n QUESTION:\n ${textBody}\n `,\n });\n return new Response(transformServerSentEvents(answer));\n }\n\n const promptId = parsedRequest.trigger.promptId;\n const promptObject = await space.crud.query({ id: promptId }).first();\n\n if (parsedRequest.data.objects.length !== 1) {\n return new Response('Message batches not supported.');\n }\n\n const messageId = parsedRequest.data.objects[0];\n let message;\n try {\n message = await space.crud.query({ id: messageId }).first();\n } catch (err) {\n return new Response('Message not replicated yet.', { status: 409 });\n }\n\n if (message.text.includes('--------')) {\n return new Response('Message was already processed.');\n }\n\n let prompt = promptObject.template;\n for (const input of promptObject.inputs) {\n let value: string | null = null;\n if (input.type === ChainInputType.VALUE) {\n value = String(input.value);\n } else if (input.type === ChainInputType.RETRIEVER) {\n value = await getContext({ space });\n } else if (input.type === ChainInputType.PASS_THROUGH) {\n value = message.text;\n }\n if (value) {\n prompt = prompt.replaceAll(`{${input.name}}`, value);\n }\n }\n\n const answer = await ai.run('@cf/meta/llama-3.1-8b-instruct', {\n stream: false,\n prompt,\n });\n const response = { response: answer.response, prompt, message };\n const textWithAnswer = message.text + '\\n--------\\n\\n' + answer.response;\n await space.crud.update({ id: messageId }, { text: textWithAnswer });\n\n return new Response(JSON.stringify(response));\n};\n\nconst getContext = async ({ space }: any) => {\n let context = '';\n const { objects: docs } = await space.crud.query({ __typename: 'dxos.org/type/Document' }).run();\n for (const doc of docs) {\n const { content } = await space.crud.query({ id: doc.content }).first();\n context += content + '\\n\\n';\n }\n return context;\n};\n\nenum ChainInputType {\n VALUE = 0,\n PASS_THROUGH = 1,\n RETRIEVER = 2,\n FUNCTION = 3,\n QUERY = 4,\n RESOLVER = 5,\n CONTEXT = 6,\n SCHEMA = 7,\n}\n", "// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n// @ts-ignore\nimport { Chess } from 'https://esm.sh/chess.js@0.13.1';\n\nexport default defineFunction({\n description: 'Plays a random move in a chess game.',\n\n inputSchema: S.Struct({\n changedObjectId: S.String.annotations({\n description: 'The objects to play the game on.',\n }),\n player: S.optional(S.Literal('w', 'b')).annotations({\n description: 'The player to play the game as.',\n }),\n }),\n\n outputSchema: S.Struct({\n state: S.String.annotations({\n description: 'The state of the game as an ASCII art board.',\n }),\n }),\n\n handler: async ({\n event: {\n data: { changedObjectId, player = 'b' },\n },\n context: { space },\n }: any) => {\n const { pgn } = await space.db.query({ id: changedObjectId }).first();\n const game = new Chess();\n game.load_pgn(pgn);\n if (game.turn() !== player) {\n return new Response('Invalid turn', { status: 409 });\n }\n\n const moves = game.moves();\n const move = moves[Math.floor(Math.random() * moves.length)];\n if (!move) {\n return new Response('No legal moves', { status: 406 });\n }\n\n game.move(move);\n const newPgn = game.pgn();\n await space.db.update({ id: changedObjectId }, { pgn: newPgn, fen: game.fen() });\n return { state: game.ascii() };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { createStatic, EchoObject, defineFunction, DXN, Filter, ObjectId, S } from 'dxos:functions';\nimport {\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { DiscordConfig, DiscordREST, DiscordRESTMemoryLive } from 'https://esm.sh/dfx@0.113.0?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Config, Redacted, Ref } from 'https://esm.sh/effect@3.13.3';\n\nconst MessageSchema = S.Struct({\n id: S.String,\n foreignId: S.Any, // bigint?\n from: S.String,\n created: S.String,\n content: S.String,\n}).pipe(EchoObject('example.com/type/Message', '0.1.0'));\n\nconst DEFAULT_AFTER = 1704067200; // 2024-01-01\n\nconst generateSnowflake = (unixTimestamp: number): bigint => {\n const discordEpoch = 1420070400000n; // Discord Epoch (ms)\n return (BigInt(unixTimestamp * 1000) - discordEpoch) << 22n;\n};\n\nexport default defineFunction({\n inputSchema: S.Struct({\n // TODO(wittjosiah): Remove. This is used to provide a terminal for a cron trigger.\n tick: S.optional(S.String),\n channelId: S.String,\n after: S.optional(S.Number),\n pageSize: S.optional(S.Number),\n queueId: S.String,\n }),\n\n outputSchema: S.Struct({\n newMessages: S.Number,\n }),\n\n handler: ({\n event: {\n data: { channelId, queueId, after = DEFAULT_AFTER, pageSize = 5 },\n },\n context: { space },\n }: any) =>\n Effect.gen(function* () {\n const { token } = yield* Effect.tryPromise(() =>\n space.db.query(Filter.typename('dxos.org/type/AccessToken', { source: 'discord.com' })).first(),\n );\n const { objects } = yield* Effect.tryPromise(() => space.queues.queryQueue(DXN.parse(queueId)));\n const backfill = objects.length === 0;\n const newMessages = yield* Ref.make(0);\n const lastMessage = yield* Ref.make(objects.at(-1));\n\n const enqueueMessages = Effect.gen(function* () {\n const rest = yield* DiscordREST;\n\n while (true) {\n const last = yield* Ref.get(lastMessage);\n const options = {\n after: backfill && !last ? `${generateSnowflake(after)}` : last?.foreignId,\n limit: pageSize,\n };\n const messages = yield* rest.getChannelMessages(channelId, options).pipe((res: any) => res.json);\n const queueMessages = messages\n .map((message: any) =>\n createStatic(MessageSchema, {\n id: ObjectId.random(),\n foreignId: message.id,\n from: message.author.username,\n created: message.timestamp,\n content: message.content,\n }),\n )\n .toReversed();\n if (queueMessages.length > 0) {\n yield* Effect.tryPromise(() => space.queues.insertIntoQueue(DXN.parse(queueId), queueMessages));\n yield* Ref.update(newMessages, (n: any) => n + queueMessages.length);\n yield* Ref.update(lastMessage, (m: any) => queueMessages.at(-1));\n }\n if (messages.length < pageSize) {\n break;\n }\n }\n }).pipe(\n Effect.provide(DiscordRESTMemoryLive),\n Effect.provide(\n DiscordConfig.layerConfig({\n token: Config.succeed(Redacted.make(token)),\n }),\n ),\n Effect.provide(FetchHttpClient.layer),\n );\n\n yield* enqueueMessages;\n return { newMessages: yield* Ref.get(newMessages) };\n }),\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Echos the request data.\n */\nexport default async ({\n event: {\n data: { request },\n },\n}: any) => {\n const data = await request.json();\n return new Response(JSON.stringify(data ?? {}), {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Appends a message to the end of a Document configured through a trigger.\n * Trigger must have a targetDocumentId field set in Meta.\n */\nexport default async ({\n event: {\n data: { request },\n },\n context: { space },\n}: any) => {\n const { data, trigger } = (await request.json()) as RequestPayload;\n\n const documentId = trigger.meta.targetDocumentId;\n const document = await space.db.query({ id: documentId }, { format: 'plain' }).first();\n\n const contentId = document.content['/'].split(':')[3];\n const documentContent = await space.db.query({ id: contentId }, { format: 'plain' }).first();\n const modifiedContent = [\n documentContent.content,\n '',\n '---',\n `**From:** ${data.from}`,\n `**Subject:** ${data.subject}`,\n `**Date:** ${data.created}`,\n '',\n data.body,\n ].join('\\n');\n\n await space.db.update({ id: contentId }, { content: modifiedContent });\n\n return new Response(JSON.stringify({ success: true }));\n};\n\ntype RequestPayload = {\n data: { from: string; subject: string; created: string; body: string };\n trigger: { meta: { targetDocumentId: string } };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\nimport {\n HttpClient,\n HttpClientRequest,\n FetchHttpClient,\n // @ts-ignore\n} from 'https://esm.sh/@effect/platform@0.77.2?deps=effect@3.13.3';\n// @ts-ignore\nimport { Effect, Schedule } from 'https://esm.sh/effect@3.13.3';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n outputSchema: S.String.annotations({ description: 'The exchange rate between the two currencies' }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) =>\n Effect.gen(function* () {\n const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(\n HttpClient.execute,\n Effect.flatMap((res: any) => res.json),\n Effect.timeout('1 second'),\n Effect.retry(Schedule.exponential(1000).pipe(Schedule.compose(Schedule.recurs(3)))),\n Effect.scoped,\n );\n return res.data.rates[to].toString();\n }).pipe(Effect.provide(FetchHttpClient.layer)),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// @ts-ignore\nimport { defineFunction, S } from 'dxos:functions';\n\nexport default defineFunction({\n description: 'Returns the exchange rate between two currencies.',\n\n inputSchema: S.Struct({\n from: S.String.annotations({ description: 'The source currency' }),\n to: S.String.annotations({ description: 'The target currency' }),\n }),\n\n handler: async ({\n event: {\n data: { from, to },\n },\n }: any) => {\n const res = await fetch(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`);\n const {\n data: { rates },\n } = await res.json();\n\n return rates[to].toString();\n },\n});\n", "//\n// Copyright 2024 DXOS.org\n//\n\n// @ts-ignore\nimport chat from './chat.ts?raw';\n// @ts-ignore\nimport chess from './chess.ts?raw';\n// @ts-ignore\nimport discord from './discord.ts?raw';\n// @ts-ignore\nimport echo from './echo.ts?raw';\n// @ts-ignore\nimport email from './email.ts?raw';\n// @ts-ignore\nimport forexEffect from './forex-effect.ts?raw';\n// @ts-ignore\nimport forex from './forex.ts?raw';\n\nconst removeHeader = (str: string) => str.split('\\n').slice(4).join('\\n');\n\nexport type Template = {\n id: string;\n name: string;\n source: string;\n presetId?: string;\n};\n\nexport const templates: Template[] = [\n {\n id: 'dxos.org/script/echo',\n name: 'Echo',\n source: removeHeader(echo),\n },\n {\n id: 'dxos.org/script/forex',\n name: 'Forex',\n source: removeHeader(forex),\n },\n {\n id: 'dxos.org/script/forex-effect',\n name: 'Forex (Effect)',\n source: removeHeader(forexEffect),\n },\n {\n id: 'dxos.org/script/gpt',\n name: 'Gpt',\n source: removeHeader(chat),\n presetId: 'dxos.org/function/gpt',\n },\n {\n id: 'dxos.org/script/chess',\n name: 'Chess',\n source: removeHeader(chess),\n presetId: 'dxos.org/function/chess',\n },\n {\n id: 'dxos.org/script/email',\n name: 'Email',\n source: removeHeader(email),\n presetId: 'dxos.org/function/email',\n },\n {\n id: 'dxos.org/script/discord',\n name: 'Discord',\n source: removeHeader(discord),\n presetId: 'dxos.org/function/discord',\n },\n];\n"],
|
|
5
|
+
"mappings": ";;;AAAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACAA;;;ACmBA,IAAMA,eAAe,CAACC,QAAgBA,IAAIC,MAAM,IAAA,EAAMC,MAAM,CAAA,EAAGC,KAAK,IAAA;AAS7D,IAAMC,YAAwB;EACnC;IACEC,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaS,YAAAA;EACvB;EACA;IACEH,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaU,aAAAA;EACvB;EACA;IACEJ,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaW,oBAAAA;EACvB;EACA;IACEL,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAaY,YAAAA;IACrBC,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAac,aAAAA;IACrBD,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAae,aAAAA;IACrBF,UAAU;EACZ;EACA;IACEP,IAAI;IACJC,MAAM;IACNC,QAAQR,aAAagB,eAAAA;IACrBH,UAAU;EACZ;;",
|
|
6
|
+
"names": ["removeHeader", "str", "split", "slice", "join", "templates", "id", "name", "source", "echo", "forex", "forexEffect", "chat", "presetId", "chess", "email", "discord"]
|
|
7
|
+
}
|
|
@@ -60,7 +60,7 @@ import { FunctionType, getInvocationUrl, getUserFunctionUrlInMetadata } from "@d
|
|
|
60
60
|
import { log } from "@dxos/log";
|
|
61
61
|
import { useClient as useClient2 } from "@dxos/react-client";
|
|
62
62
|
import { Filter, getMeta, getSpace, useQuery } from "@dxos/react-client/echo";
|
|
63
|
-
import { Button as Button2, Clipboard, Input, Separator,
|
|
63
|
+
import { Button as Button2, Clipboard, Input, Separator, useControlledState, useTranslation as useTranslation2 } from "@dxos/react-ui";
|
|
64
64
|
import { AccessTokenType } from "@dxos/schema";
|
|
65
65
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/plugins/experimental/plugin-script/src/components/ScriptSettingsPanel.tsx";
|
|
66
66
|
var kebabize = (str) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? "-" : "") + $.toLowerCase());
|
|
@@ -108,7 +108,7 @@ var ScriptSettingsPanel = ({ script }) => {
|
|
|
108
108
|
githubToken,
|
|
109
109
|
gistKey
|
|
110
110
|
]);
|
|
111
|
-
const [binding, setBinding] =
|
|
111
|
+
const [binding, setBinding] = useControlledState(fn?.binding ?? "");
|
|
112
112
|
const handleBindingChange = useCallback((event) => {
|
|
113
113
|
setBinding(event.target.value);
|
|
114
114
|
}, [
|
|
@@ -168,7 +168,19 @@ var ScriptSettingsPanel = ({ script }) => {
|
|
|
168
168
|
script,
|
|
169
169
|
githubToken
|
|
170
170
|
]);
|
|
171
|
-
return /* @__PURE__ */ React2.createElement(React2.Fragment, null,
|
|
171
|
+
return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("div", {
|
|
172
|
+
role: "form",
|
|
173
|
+
className: "flex flex-col w-full p-2 gap-4"
|
|
174
|
+
}, /* @__PURE__ */ React2.createElement(Input.Root, null, /* @__PURE__ */ React2.createElement("div", {
|
|
175
|
+
role: "none",
|
|
176
|
+
className: "flex flex-col gap-1"
|
|
177
|
+
}, /* @__PURE__ */ React2.createElement(Input.Label, null, t("description label")), /* @__PURE__ */ React2.createElement(Input.TextInput, {
|
|
178
|
+
placeholder: t("description placeholder"),
|
|
179
|
+
value: script.description ?? "",
|
|
180
|
+
onChange: (event) => {
|
|
181
|
+
script.description = event.target.value;
|
|
182
|
+
}
|
|
183
|
+
})))), fn && functionUrl && /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(Separator, null), /* @__PURE__ */ React2.createElement("div", {
|
|
172
184
|
role: "form",
|
|
173
185
|
className: "flex flex-col w-full p-2 gap-4"
|
|
174
186
|
}, /* @__PURE__ */ React2.createElement("h2", null, t("remote function settings heading")), /* @__PURE__ */ React2.createElement(Input.Root, null, /* @__PURE__ */ React2.createElement("div", {
|
|
@@ -213,8 +225,8 @@ var ScriptSettingsPanel = ({ script }) => {
|
|
|
213
225
|
|
|
214
226
|
// packages/plugins/experimental/plugin-script/src/components/index.ts
|
|
215
227
|
import { lazy } from "react";
|
|
216
|
-
var AutomationPanel = lazy(() => import("./AutomationPanel-
|
|
217
|
-
var ScriptContainer = lazy(() => import("./ScriptContainer-
|
|
228
|
+
var AutomationPanel = lazy(() => import("./AutomationPanel-WTVVVMRH.mjs"));
|
|
229
|
+
var ScriptContainer = lazy(() => import("./ScriptContainer-MHRJXMC4.mjs"));
|
|
218
230
|
|
|
219
231
|
export {
|
|
220
232
|
ScriptSettings,
|
|
@@ -222,4 +234,4 @@ export {
|
|
|
222
234
|
AutomationPanel,
|
|
223
235
|
ScriptContainer
|
|
224
236
|
};
|
|
225
|
-
//# sourceMappingURL=chunk-
|
|
237
|
+
//# sourceMappingURL=chunk-IAELQPSI.mjs.map
|