@surph_ai/sdk 0.0.17 → 0.0.19

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.
@@ -1,19 +1,15 @@
1
- const tool = require('./dist/tools')
1
+ import tool from './dist/tools/index.js';
2
2
 
3
- const handler = async (event) => {
3
+ export const handler = async (event) => {
4
4
  const { args = {} } = event;
5
5
  let payload = null;
6
6
  try {
7
- payload = await tool(args);
7
+ payload = await tool(args);
8
+ } catch (error) {
9
+ payload = error instanceof Error ? error.message : String(error);
8
10
  }
9
- catch (error) {
10
- payload = error instanceof Error ? error.message : String(error);
11
- }
12
- const response = {
13
- statusCode: 200,
14
- body: JSON.stringify(payload),
11
+ return {
12
+ statusCode: 200,
13
+ body: JSON.stringify(payload),
15
14
  };
16
- return response;
17
15
  };
18
-
19
- exports.handler = handler;
package/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  const { Command } = require('commander')
10
10
  const path = require('path')
11
+ const fs = require('fs')
11
12
  const dotenv = require('dotenv')
12
13
  const prompt = require('prompt')
13
14
  const shell = require('shelljs')
@@ -36,6 +37,23 @@ const ERRORS = {
36
37
  NOT_AUTHORIZED: { exitCode: 102 },
37
38
  };
38
39
 
40
+ const surphSession = async () => {
41
+ try {
42
+ const userSessionPath = path.resolve(__dirname, '../../../.surph/session.json')
43
+ if (!fs.existsSync(userSessionPath)) {
44
+ console.log('Not logged in.')
45
+ return null
46
+ }
47
+
48
+ const file = fs.readFileSync(userSessionPath, 'utf-8')
49
+ const session = JSON.parse(file)
50
+ return session
51
+ } catch (error) {
52
+ console.log('Not logged in.')
53
+ return null
54
+ }
55
+ }
56
+
39
57
  const program = new Command()
40
58
 
41
59
  program.version(VERSION, '-v, --version', 'output the current version')
@@ -61,14 +79,24 @@ program.command('version')
61
79
  program.command('profile')
62
80
  .description('Current Surph user')
63
81
  .action(async (cmd, options) => {
64
- const user = await auth.currentUser()
65
- if (user === false) {
66
- program.error(`${colors.cyan('\nNot logged in. To log in:')}\n\n${colors.white('$ vly login')}`,
67
- ERRORS.NOT_LOGGED_IN);
68
- }
69
-
70
- const text = `${colors.cyan(`\nLogged in as: `)} ${colors.brightGreen(`${user.username}`)}\n`
71
- console.log(text)
82
+ // const userSessionPath = path.resolve(__dirname, '../../../.surph/session.json')
83
+ // if (!fs.existsSync(userSessionPath)) {
84
+ // console.log('SESSION NOT FOUND:')
85
+ // return
86
+ // }
87
+
88
+ // const file = fs.readFileSync(userSessionPath, 'utf-8')
89
+ // const data = JSON.parse(file)
90
+ // console.log('SESSION FOUND:' + JSON.stringify(data))
91
+
92
+ // const user = await auth.currentUser()
93
+ // if (user === false) {
94
+ // program.error(`${colors.cyan('\nNot logged in. To log in:')}\n\n${colors.white('$ vly login')}`,
95
+ // ERRORS.NOT_LOGGED_IN);
96
+ // }
97
+
98
+ // const text = `${colors.cyan(`\nLogged in as: `)} ${colors.brightGreen(`${user.username}`)}\n`
99
+ // console.log(text)
72
100
  })
73
101
 
74
102
  /*
@@ -230,24 +258,38 @@ program.command('publish')
230
258
  .description('Publish Surph tool')
231
259
  .action(async (cmd, options) => {
232
260
  try {
233
- const manifest = require('../../../tools/manifest.json')
234
-
235
- // TODO: if not found try root directory.
261
+ const manifest = require('../../../manifest.json')
236
262
  if (!manifest) {
237
263
  throw new Error('manifest.json not found')
238
264
  }
239
265
 
240
266
  const keys = Object.keys(manifest)
241
267
  if (keys.length === 0) {
242
- throw new Error('invalide manifest.json')
268
+ throw new Error('invalid manifest.json')
243
269
  }
244
270
 
245
- const slug = keys[0]
271
+ const session = await surphSession()
272
+ if (!session) {
273
+ throw new Error('Not logged in.')
274
+ }
275
+
276
+ // console.log('SESSION: ' + JSON.stringify(session))
277
+ const userId = session?.userId
278
+
279
+ let resp = await fetch(`${SURPH_REST_URL}/rest/user/${userId}`, {
280
+ method: 'GET',
281
+ headers: {
282
+ Accept: 'application/json',
283
+ 'x-surph-client': 'surph-sdk'
284
+ }
285
+ })
286
+
287
+ const { payload: user } = await resp.json()
288
+ // console.log('USER: ' + JSON.stringify(user))
246
289
 
247
- // console.log('Publish Surph tool: ' + JSON.stringify(manifest[slug]))
248
290
 
249
- const url = `${SURPH_REST_URL}/rest/tool?slug=${slug}`
250
- let resp = await fetch(url, {
291
+ const slug = keys[0]
292
+ resp = await fetch(`${SURPH_REST_URL}/rest/tool?slug=${slug}`, {
251
293
  method: 'GET',
252
294
  headers: {
253
295
  Accept: 'application/json',
@@ -257,11 +299,20 @@ program.command('publish')
257
299
 
258
300
  const { payload } = await resp.json()
259
301
 
302
+ const toolJson = manifest[slug]
303
+
260
304
  // tool not registered yet, create:
261
305
  if (payload.length === 0) {
262
306
  const resp = await fetch(url, {
263
307
  method: 'POST',
264
- body: JSON.stringify(manifest[slug]),
308
+ body: JSON.stringify({
309
+ ...toolJson,
310
+ creator: {
311
+ _id: user._id,
312
+ username: user.username,
313
+ avatar: user.avatar
314
+ }
315
+ }),
265
316
  headers: {
266
317
  Accept: 'application/json',
267
318
  'Content-Type': 'application/json',
@@ -276,7 +327,14 @@ program.command('publish')
276
327
 
277
328
  resp = await fetch(`${SURPH_REST_URL}/rest/tool/${payload[0]._id}`, {
278
329
  method: 'PUT',
279
- body: JSON.stringify(manifest[slug]),
330
+ body: JSON.stringify({
331
+ ...toolJson,
332
+ creator: {
333
+ _id: user._id,
334
+ username: user.username,
335
+ avatar: user.avatar
336
+ }
337
+ }),
280
338
  headers: {
281
339
  Accept: 'application/json',
282
340
  'Content-Type': 'application/json',
@@ -285,11 +343,9 @@ program.command('publish')
285
343
  })
286
344
 
287
345
  const data = await resp.json()
288
- console.log('\nSurph tool updated: ' + JSON.stringify(data.payload))
289
-
290
-
346
+ console.log('\nSurph tool updated.')
291
347
  } catch (error) {
292
-
348
+ console.log(colors.red('\nError: '+error.message+'\n'))
293
349
  }
294
350
  })
295
351
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surph_ai/sdk",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "publishConfig": {
package/scaffold/index.js CHANGED
@@ -119,10 +119,11 @@ module.exports = (name, type = 'app') => {
119
119
  const envStr = utils.readFile(path.join(__dirname, 'tool/env.txt'))
120
120
  utils.write('.env', envStr.replace('<SURPH_TOOL>', slug))
121
121
 
122
- utils.write('tsconfig.json', JSON.stringify({
122
+ const tsConfig = {
123
123
  "compilerOptions": {
124
124
  "target": "ES2022",
125
- "module": "commonjs",
125
+ "module": "Node16",
126
+ "moduleResolution": "Node16",
126
127
  "lib": ["ES2022"],
127
128
  "types": ["node"],
128
129
  "outDir": "./dist",
@@ -135,7 +136,9 @@ module.exports = (name, type = 'app') => {
135
136
  },
136
137
  "include": ["tools/**/*.ts"],
137
138
  "exclude": ["node_modules", "dist"]
138
- }, null, 2) + '\n')
139
+ }
140
+
141
+ utils.write('tsconfig.json', JSON.stringify(tsConfig, null, 2) + '\n')
139
142
 
140
143
  console.log('\n- - - - - Next Steps - - - - - ')
141
144
  console.log('1. $ cd ' + name)
@@ -2,6 +2,7 @@
2
2
  "name": "tool-template",
3
3
  "version": "0.0.0",
4
4
  "private": true,
5
+ "type": "module",
5
6
  "scripts": {
6
7
  "dev": "npm run build && concurrently \"npm run watch\" \"surph toolserver\" \"surph chatserver\"",
7
8
  "test": "",
@@ -14,7 +15,7 @@
14
15
  "@vinely-ai/sdk": "^0.0.6"
15
16
  },
16
17
  "devDependencies": {
17
- "@surph_ai/sdk": "^0.0.16",
18
+ "@surph_ai/sdk": "^0.0.17",
18
19
  "@types/node": "^20.11.0",
19
20
  "concurrently": "^10.0.5",
20
21
  "nodemon": "^2.0.2",
package/toolserver/app.js CHANGED
@@ -8,6 +8,14 @@ vinely.configureApp(app, {
8
8
  static: 'public',
9
9
  })
10
10
 
11
+ app.use((req, res, next) => {
12
+ res.setHeader('Access-Control-Allow-Origin', '*')
13
+ res.header('Access-Control-Allow-Headers', 'x-surph-user, Content-Type');
14
+ res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
15
+ if (req.method === 'OPTIONS') return res.sendStatus(204);
16
+ next()
17
+ })
18
+
11
19
  const index = require('./routes/index')
12
20
  const tool = require('./routes/tool')
13
21
 
@@ -1,11 +1,23 @@
1
+ const fs = require('fs')
2
+ const path = require('path')
3
+ const os = require('os')
1
4
  const { Router, response } = require('express')
2
- // const tools = require('../../../../../tools')
3
- const tools = require('../../../../../dist/tools')
5
+ const { pathToFileURL } = require('url')
4
6
  const manifest = require('../../../../../manifest.json')
5
7
 
8
+ const SESSION_DIR = path.resolve(__dirname, '../../../../../.surph')
9
+ const SESSION_FILE = path.join(SESSION_DIR, 'session.json')
10
+
11
+ const toolsPath = pathToFileURL(
12
+ path.resolve(__dirname, '../../../../../dist/tools/index.js')
13
+ ).href
14
+
15
+ const loadTool = () => import(toolsPath).then((mod) => mod.default)
16
+
6
17
  const router = Router()
7
18
 
8
19
  const handler = async (args, tool) => {
20
+ console.log('HANDLER: ' + JSON.stringify(Object.keys(tool)))
9
21
  let payload = null
10
22
  let errorMsg = null
11
23
  try {
@@ -26,6 +38,24 @@ const handler = async (args, tool) => {
26
38
  }
27
39
 
28
40
  router.get('/', async (req, res, next) => {
41
+ const surphUser = req.headers['x-surph-user']
42
+ if (surphUser) {
43
+ try {
44
+ // console.log('SAVE SURPH USER: ' + surphUser)
45
+ fs.mkdirSync(SESSION_DIR, { recursive: true, mode: 0o700 })
46
+ fs.writeFileSync(
47
+ SESSION_FILE,
48
+ JSON.stringify({
49
+ userId: surphUser,
50
+ updatedAt: new Date().toISOString()
51
+ }, null, 2),
52
+ { mode: 0o600 }
53
+ )
54
+ } catch (error) {
55
+ console.warn('[sdk] session write failed:', error.message)
56
+ }
57
+ }
58
+
29
59
  try {
30
60
  res.json({ response: manifest })
31
61
  } catch (error) {
@@ -38,13 +68,13 @@ router.get('/', async (req, res, next) => {
38
68
  }
39
69
  })
40
70
 
41
- router.get('/:tool', async (req, res, next) => {
71
+ router.get('/test', async (req, res, next) => {
42
72
  try {
43
- // const tool = tools[req.params.tool]
44
- // if (!tool) {
45
- // throw new Error(`Tool ${req.params.tool} not found.`)
46
- // }
73
+ if (Object.keys(req.query).length === 0) {
74
+ throw new Error('No arguments provided.')
75
+ }
47
76
 
77
+ const tools = await loadTool()
48
78
  const response = await handler(req.query, tools)
49
79
  res.json({ response })
50
80
  } catch (error) {
@@ -68,10 +98,12 @@ router.post('/custom', async (req, res, next) => {
68
98
  throw new Error(`Invalid tool ${tool.slug}. Check .env file.`)
69
99
  }
70
100
 
101
+ const tools = await loadTool()
71
102
  const response = await handler(args, tools)
72
103
  // console.log('TOOL RESP: ' + JSON.stringify(response))
73
104
  res.json({ response })
74
105
  } catch (error) {
106
+ // console.log('TOOL ERR: ' + error.message)
75
107
  res.json({
76
108
  response: {
77
109
  success: false,